Avoid branching to make exclusive systems faster
Author: alice-i-cecileCreated Sep 28, 2026Updated Sep 28, 2026
LabelsX-Uncontroversial
I threw together a benchmark.
pub fn alternate_regular_exclusive_system(criterion: &mut Criterion) {
fn s_0(mut q_0: Query<(&mut A, &mut B)>) {
// q_0.iter_mut().for_each(|(mut c_0, mut c_1)| {
// core::mem::swap(&mut c_0.0, &mut c_1.0);
// });
}
fn s_2(world: &mut World, q_0: &mut QueryState<(&mut C, &mut D)>) {
// q_0.iter_mut(world).for_each(|(mut c_0, mut c_1)| {
// core::mem::swap(&mut c_0.0, &mut c_1.0);
// });
}
let mut world = World::new();
let mut group = criterion.benchmark_group("contrived");
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(3));
let mut system = IntoSystem::into_system(s_0);
let mut exclusive_system = IntoSystem::into_system(s_2);
system.initialize(&mut world);
exclusive_system.initialize(&mut world);
group.bench_function("alternate_regular_exclusive_system", |bencher| {
bencher.iter(|| {
let _ = system.run((), &mut world);
let _ = exclusive_system.run((), &mut world);
});
});
group.finish();
}which goes from 3.2ns to 11ns with this pr. Not going to block for 7ns. But we should see if we can reduce that with an associated const to get rid of branching on self.exclusive.
Originally posted by @hymm in https://github.com/bevyengine/bevy/pull/25864#pullrequestreview-5333233254
Source: bevyengine/bevy