From eee71bfa935b1a9fd0492f97d0d9fb693227adb2 Mon Sep 17 00:00:00 2001 From: James Liu Date: Mon, 12 Feb 2024 07:19:36 -0800 Subject: [PATCH] Put asset_events behind a run condition (#11800) # Objective Scheduling low cost systems has significant overhead due to task pool contention and the extra machinery to schedule and run them. Following the example of #7728, `asset_events` is good example of this kind of system, where there is no work to be done when there are no queued asset events. ## Solution Put a run condition on it that checks if there are any queued events. ## Performance Tested against `many_foxes`, we can see a slight improvement in the total time spent in `UpdateAssets`. Also noted much less volatility due to not being at the whim of the OS thread scheduler. ![image](https://github.com/bevyengine/bevy/assets/3137680/e0b282bf-27d0-4fe4-81b9-ecd72ab258e5) --------- Co-authored-by: Alice Cecile --- crates/bevy_asset/src/assets.rs | 8 ++++++++ crates/bevy_asset/src/lib.rs | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/bevy_asset/src/assets.rs b/crates/bevy_asset/src/assets.rs index 3248606cc9..0a4fe716fb 100644 --- a/crates/bevy_asset/src/assets.rs +++ b/crates/bevy_asset/src/assets.rs @@ -536,6 +536,14 @@ impl Assets { pub fn asset_events(mut assets: ResMut, mut events: EventWriter>) { events.send_batch(assets.queued_events.drain(..)); } + + /// A run condition for [`asset_events`]. The system will not run if there are no events to + /// flush. + /// + /// [`asset_events`]: Self::asset_events + pub(crate) fn asset_events_condition(assets: Res) -> bool { + !assets.queued_events.is_empty() + } } /// A mutable iterator over [`Assets`]. diff --git a/crates/bevy_asset/src/lib.rs b/crates/bevy_asset/src/lib.rs index 4f0d259d45..41d6ef834f 100644 --- a/crates/bevy_asset/src/lib.rs +++ b/crates/bevy_asset/src/lib.rs @@ -386,7 +386,10 @@ impl AssetApp for App { .add_event::>() .register_type::>() .register_type::>() - .add_systems(AssetEvents, Assets::::asset_events) + .add_systems( + AssetEvents, + Assets::::asset_events.run_if(Assets::::asset_events_condition), + ) .add_systems(UpdateAssets, Assets::::track_assets.in_set(TrackAssets)) }