Skip to content

Commit

Permalink
Try optimizing by acquiring RwLock fewer time
Browse files Browse the repository at this point in the history
  • Loading branch information
goodhoko committed Aug 6, 2024
1 parent d4622ae commit 3f2cd77
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -736,16 +736,27 @@ impl SystemHandle {
&self,
recipient: Recipient<M>,
) -> Result<(), SendError> {
let mut event_subscribers = self.event_subscribers.write();

// Send the last cached value (if there is one)
if let Some(last_cached_value) =
self.event_subscribers.read().last_value_cache.get(&TypeId::of::<E>())
if let Some(last_cached_value) = event_subscribers.last_value_cache.get(&TypeId::of::<E>())
{
if let Some(msg) = last_cached_value.downcast_ref::<E>() {
recipient.send(msg.clone().into())?;
}
}

self.subscribe_recipient::<M, E>(recipient);
// Duplicate the contents of Self::subscribe_recipient() to reuse the same WriteGuard
// for better performance.
let subs = event_subscribers.events.entry(TypeId::of::<E>()).or_default();
subs.push(Box::new(move |e| {
if let Some(event) = e.downcast_ref::<E>() {
let msg = event.clone();
recipient.send(msg.into())?;
}

Ok(())
}));

Ok(())
}
Expand Down Expand Up @@ -1325,9 +1336,9 @@ mod tests {

struct Subscriber;
impl Actor for Subscriber {
type Message = ();
type Context = Context<Self::Message>;
type Error = ();
type Message = ();

fn started(&mut self, context: &mut Self::Context) {
context
Expand Down

0 comments on commit 3f2cd77

Please sign in to comment.