diff --git a/CHANGELOG.md b/CHANGELOG.md index 66a4e280f5..ba22f10ba6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update. - Remove fns `SeedableRng::from_os_rng`, `try_from_os_rng` (#1674) - Remove `Clone` support for `StdRng`, `ReseedingRng` (#1677) - Use `postcard` instead of `bincode` to test the serde feature (#1693) +- Avoid excessive allocation in `IteratorRandom::sample` when `amount` is much larger than iterator size ### Additions - Add fns `IndexedRandom::choose_iter`, `choose_weighted_iter` (#1632) diff --git a/src/seq/iterator.rs b/src/seq/iterator.rs index 187ca3c055..65ccb987b6 100644 --- a/src/seq/iterator.rs +++ b/src/seq/iterator.rs @@ -245,8 +245,7 @@ pub trait IteratorRandom: Iterator + Sized { where R: Rng + ?Sized, { - let mut reservoir = Vec::with_capacity(amount); - reservoir.extend(self.by_ref().take(amount)); + let mut reservoir = Vec::from_iter(self.by_ref().take(amount)); // Continue unless the iterator was exhausted // @@ -259,10 +258,6 @@ pub trait IteratorRandom: Iterator + Sized { *slot = elem; } } - } else { - // Don't hang onto extra memory. There is a corner case where - // `amount` was much less than `self.len()`. - reservoir.shrink_to_fit(); } reservoir }