Element Storage: Pointer-Owned vs Value-Owned Elements
Question 49 / 51 • Correct so far: 0 (0 answered)
Ptr Vector
std::vector<std::unique_ptr<Widget>> makeWidgets() {
std::vector<std::unique_ptr<Widget>> v;
v.reserve(kNumWidgets);
for (int i = 0; i < kNumWidgets; ++i)
v.push_back(std::make_unique<Widget>(i, static_cast<float>(i)));
return v;
}
long long sum = 0;
for (const auto& p : PTR_WIDGETS)
sum += p->id;
benchmark::DoNotOptimize(sum); Value Vector
std::vector<Widget> makeWidgets() {
std::vector<Widget> v;
v.reserve(kNumWidgets);
for (int i = 0; i < kNumWidgets; ++i)
v.push_back(Widget{i, static_cast<float>(i)});
return v;
}
long long sum = 0;
for (const auto& w : VAL_WIDGETS)
sum += w.id;
benchmark::DoNotOptimize(sum); Shared test data (shared-setup)
struct Widget {
Widget(int i, float v) : id(i), value(v) {}
int id;
float value;
};
constexpr int kNumWidgets = 4096; Which snippet is faster?
Snippet B is faster. vector<T> stores elements contiguously, which gives
predictable cache-friendly iteration. vector<unique_ptr<T>> adds pointer
indirection and scattered allocations, increasing cache misses.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Ptr Vector | 1.13 us | 1.0× |
| Value Vector | 206 ns | 5.5× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.