-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
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 a Vec with with_capacity is often faster than using SmallVec 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 to new with with_capacity and .collect() will still use the same minimum allocation size (although this is rarely a problem because of size_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.