Skip to content

Commit b88c894

Browse files
committed
Do not allocate capacity in ready_chunks
`read_chunks` practically often returns items when not all capacity filled. So always allocating full capacity results in excessive allocation. This is especially an issue when `capacity` parameter passed is large (to be able to handle streams efficiently under high load).
1 parent 3c657e5 commit b88c894

File tree

1 file changed

+3
-10
lines changed

1 file changed

+3
-10
lines changed

futures-util/src/stream/stream/ready_chunks.rs

+3-10
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,7 @@ impl<St: Stream> ReadyChunks<St> {
2424
pub(super) fn new(stream: St, capacity: usize) -> Self {
2525
assert!(capacity > 0);
2626

27-
Self {
28-
stream: super::Fuse::new(stream),
29-
items: Vec::with_capacity(capacity),
30-
cap: capacity,
31-
}
27+
Self { stream: super::Fuse::new(stream), items: Vec::new(), cap: capacity }
3228
}
3329

3430
delegate_access_inner!(stream, St, (.));
@@ -48,7 +44,7 @@ impl<St: Stream> Stream for ReadyChunks<St> {
4844
return if this.items.is_empty() {
4945
Poll::Pending
5046
} else {
51-
Poll::Ready(Some(mem::replace(this.items, Vec::with_capacity(*this.cap))))
47+
Poll::Ready(Some(mem::take(this.items)))
5248
}
5349
}
5450

@@ -58,10 +54,7 @@ impl<St: Stream> Stream for ReadyChunks<St> {
5854
Poll::Ready(Some(item)) => {
5955
this.items.push(item);
6056
if this.items.len() >= *this.cap {
61-
return Poll::Ready(Some(mem::replace(
62-
this.items,
63-
Vec::with_capacity(*this.cap),
64-
)));
57+
return Poll::Ready(Some(mem::take(this.items)));
6558
}
6659
}
6760

0 commit comments

Comments
 (0)