std::vector Pre-allocation: reserve vs resize
Question 31 / 51 • Correct so far: 0 (0 answered)
Reserve Assign
std::vector<int> buildVector(int n) {
std::vector<int> v;
v.reserve(n);
for (int i = 0; i < n; ++i)
v.push_back(i * 2);
return v;
}
std::vector<int> v = buildVector(kSize); Resize Assign
std::vector<int> buildVector(int n) {
std::vector<int> v;
v.resize(n);
for (int i = 0; i < n; ++i)
v[i] = i * 2;
return v;
}
std::vector<int> v = buildVector(kSize); Shared test data (shared-setup)
constexpr int kSize = 10000; Which snippet is faster?
Snippet B is faster in this benchmark. It writes values by direct index into an already sized vector, while snippet A grows the vector with push_back on every iteration. With this workload and compiler, the indexed loop is faster.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Reserve Assign | 3.75 us | 1.0× |
| Resize Assign | 647 ns | 5.8× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.