perf(pubsub): Skip clone on last message

This commit is contained in:
Rasmus Melchior Jacobsen 2023-03-21 13:25:49 +01:00
parent b6663a013f
commit ce7bd6955f

View File

@ -322,12 +322,15 @@ impl<T: Clone, const CAP: usize, const SUBS: usize, const PUBS: usize> PubSubSta
// We're reading this item, so decrement the counter
queue_item.1 -= 1;
let message = queue_item.0.clone();
if current_message_index == 0 && queue_item.1 == 0 {
self.queue.pop_front();
let message = if current_message_index == 0 && queue_item.1 == 0 {
let (message, _) = self.queue.pop_front().unwrap();
self.publisher_wakers.wake();
}
// Return pop'd message without clone
message
} else {
queue_item.0.clone()
};
Some(WaitResult::Message(message))
}
@ -659,4 +662,25 @@ mod tests {
assert_eq!(4, channel.space());
}
struct CloneCallCounter(usize);
impl Clone for CloneCallCounter {
fn clone(&self) -> Self {
Self(self.0 + 1)
}
}
#[futures_test::test]
async fn skip_clone_for_last_message() {
let channel = PubSubChannel::<NoopRawMutex, CloneCallCounter, 1, 2, 1>::new();
let pub0 = channel.publisher().unwrap();
let mut sub0 = channel.subscriber().unwrap();
let mut sub1 = channel.subscriber().unwrap();
pub0.publish(CloneCallCounter(0)).await;
assert_eq!(1, sub0.try_next_message_pure().unwrap().0);
assert_eq!(0, sub1.try_next_message_pure().unwrap().0);
}
}