Skip to content

Commit

Permalink
In ready_chunks, reserve capacity based on size_hint
Browse files Browse the repository at this point in the history
Reserving `ready_chunks` limit every time may be too expensive when
the limit is high but only a few number of messages available.

Now rely on `Stream::size_hint` to reserve the capacity.  If
underlying stream implements `size_hint`, this will work great.
Otherwise `ready_chunk` will be somewhat less efficient.

This is better alternative to #2657
  • Loading branch information
stepancheg committed Oct 30, 2022
1 parent 260f9e9 commit 19338ee
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion futures-util/src/stream/stream/ready_chunks.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::stream::Fuse;
use alloc::vec::Vec;
use core::cmp;
use core::pin::Pin;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
Expand Down Expand Up @@ -49,7 +50,11 @@ impl<St: Stream> Stream for ReadyChunks<St> {
// the full one.
Poll::Ready(Some(item)) => {
if items.is_empty() {
items.reserve(*this.cap);
// Note we reserve capacity here, not when `items` is created,
// because stream may know the remaining size,
// but items might not be readily available.
let size_hint = this.stream.as_mut().size_hint().0.wrapping_add(1);
items.reserve(cmp::min(*this.cap, size_hint));
}
items.push(item);
if items.len() >= *this.cap {
Expand Down

0 comments on commit 19338ee

Please sign in to comment.