std::vector Growth: reserve Before push_back vs Without
Question 30 / 51 • Correct so far: 0 (0 answered)
No Reserve
std::vector<int> buildVector(int n) {
std::vector<int> v;
for (int i = 0; i < n; ++i)
v.push_back(i);
return v;
}
std::vector<int> v = buildVector(kPushCount); With Reserve
std::vector<int> buildVector(int n) {
std::vector<int> v;
v.reserve(n);
for (int i = 0; i < n; ++i)
v.push_back(i);
return v;
}
std::vector<int> v = buildVector(kPushCount); Shared test data (shared-setup)
constexpr int kPushCount = 128; Which snippet is faster?
Snippet B is faster. Without reserve, std::vector doubles capacity on overflow, triggering O(log N) reallocations that copy or move all existing elements. Calling reserve(N) first allocates exactly once, so every push_back writes directly into pre-allocated memory with no reallocation.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| No Reserve | 110 ns | 1.0× |
| With Reserve | 55.8 ns | 2.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.