Description
Hey gang.
As originally determined in https://twitter.com/kot_2010/status/927119253324619776, building a pre-size-hinted mutable Vec
as the output of a loop (even for very small n
) can occasionally be more than twice as fast as collect
ing into a Vec
. As demonstrated here https://github.com/stuhood/rust-vec-bench, using extend
into a pre-size-hinted Vec
closes most of the gap.
Focusing on improving Iterator::size_hint
implementations so that they suggest better sizes for collect
would likely help reduce this gap. But there are diminishing returns to heuristics, and in many cases users should be able to give better explicit hints.
This issue initially proposed adding an Iterator::collect_with_size_hint
method, but @scottmcm 's suggestion to add Iterator::collect_into<E: Extend>(e: E) -> E
seems more general, and suggests a useful analogue in unzip_into<E1: Extend, E2: Extend>(e1: E1, e2: E2) -> (E1, E2)
.