Skip to content

Commit

Permalink
Optimize Events::extend and impl std::iter::Extend (#2207)
Browse files Browse the repository at this point in the history
The previous implementation of `Events::extend` iterated through each event and manually `sent` it via `Events:;send`.
However, this could be a minor performance hit since calling `Vec::push` in a loop is not optimal.
This refactors the code to use `Vec::extend`.
  • Loading branch information
NathanSWard committed May 19, 2021
1 parent 29bc4e3 commit a42343d
Showing 1 changed file with 41 additions and 10 deletions.
51 changes: 41 additions & 10 deletions crates/bevy_ecs/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ impl<T: Component> Events<T> {
id: self.event_count,
_marker: PhantomData,
};
trace!("Events::send() -> {}", event_id);
trace!("Events::send() -> id: {}", event_id);

let event_instance = EventInstance { event_id, event };

Expand Down Expand Up @@ -361,15 +361,6 @@ impl<T: Component> Events<T> {
}
}

pub fn extend<I>(&mut self, events: I)
where
I: Iterator<Item = T>,
{
for event in events {
self.send(event);
}
}

/// Iterates over events that happened since the last "update" call.
/// WARNING: You probably don't want to use this call. In most cases you should use an
/// `EventReader`. You should only use this if you know you only need to consume events
Expand All @@ -384,6 +375,35 @@ impl<T: Component> Events<T> {
}
}

impl<T> std::iter::Extend<T> for Events<T> {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
let mut event_count = self.event_count;
let events = iter.into_iter().map(|event| {
let event_id = EventId {
id: event_count,
_marker: PhantomData,
};
event_count += 1;
EventInstance { event_id, event }
});

match self.state {
State::A => self.events_a.extend(events),
State::B => self.events_b.extend(events),
}

trace!(
"Events::extend() -> ids: ({}..{})",
self.event_count,
event_count
);
self.event_count = event_count;
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -526,4 +546,15 @@ mod tests {
assert!(events.drain().eq(vec![E(0), E(1)].into_iter()));
});
}

#[test]
fn test_events_extend_impl() {
let mut events = Events::<TestEvent>::default();
let mut reader = events.get_reader();

events.extend(vec![TestEvent { i: 0 }, TestEvent { i: 1 }]);
assert!(reader
.iter(&events)
.eq([TestEvent { i: 0 }, TestEvent { i: 1 }].iter()));
}
}

0 comments on commit a42343d

Please sign in to comment.