rust-lang / rust-lang/rfcs

Allow specifying a minimum size for `Vec`

Open
#2,445 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-libs
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

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.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No repository files, tests, or entry points are named. Start by reading the issue and its linked profiling report, then review the const-generics context from issue #2000. Done means producing a concrete, agreed RFC for configurable initial Vec allocation behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.