Allow specifying a minimum size for Vec
#2445
Labels
T-libs-api
Relevant to the library API team, which will review and decide on the RFC.
Vec
#2445
At the moment when a vector is created it doesn't allocate anything, but then when a single element is pushed to it it grows to hold precisely 4 elements. As further elements are pushed it doubles each time. That first allocation is a problem, though. It's quite common to use
SmallVec
in performance-sensitive code when there is an "expected maximum", a value which is normally not exceeded but may be exceeded in edge-cases. However, profiling shows that using aVec
withwith_capacity
is often faster than usingSmallVec
because of the reduced complexity.This has a couple of problems though. Firstly, this isn't a drop-in replacement like
SmallVec
is. You need to replace every call tonew
withwith_capacity
and.collect()
will still use the same minimum allocation size (although this is rarely a problem because ofsize_hint
). Worst is that if you create a vector and then never push anything to it then you have a wasted allocation and deallocation.You could have a wrapper around
Vec
that checks the capacity and allocates the supplied number of elements on first allocation but that's an extra cost on every insertion. The most efficient method would be to have that "precisely 4" be configurable somehow, probably with const generics (#2000). Because this couldn't be implemented today, I have written this as an issue rather than a PR.The text was updated successfully, but these errors were encountered: