-
-
Notifications
You must be signed in to change notification settings - Fork 14.8k
Vec::reserve should use alloc_excess #71383
Copy link
Copy link
Open
Labels
A-allocatorsArea: Custom and system allocatorsArea: Custom and system allocatorsA-collectionsArea: `std::collections`Area: `std::collections`C-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
Metadata
Metadata
Assignees
Labels
A-allocatorsArea: Custom and system allocatorsArea: Custom and system allocatorsA-collectionsArea: `std::collections`Area: `std::collections`C-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
Type
Fields
Give feedbackNo fields configured for issues without a type.
When calling
reserve()on aVecwhose capacity is zero, afterwards thecapacity()method always returns the exact argument that was passed toreserve(). Even though the contract ofreserve()allowsVecto make the capacity larger than requested, if the previous capacity is zero,Vecdoes not make use of this. When the underlying allocator is bucketed, rounding to the bucket size never wastes memory, soVecshould usealloc_excessto make the slop available to the user.Use case: We're going to write at least
best_caseitems and at mostworst_caseitems, such thatbest_case < worst_case, but we don't know how many items exactly. The common case can be expected to be close tobest_casebut often at least one more. It would make sense to first allocate forbest_caserounded up to allocator bucket size, then start writing, then if not everything fits, resize toworst_case, write the rest, and finally resize to the size actually written andshrink_to_fit().This would guarantee at most three allocations and in the common case one.
This issues comes up often with low-level string code.