shared_ptr in a Loop: Copy per Iteration vs. Reuse Handle
Question 32 / 51 • Correct so far: 0 (0 answered)
Shared Ptr Loop Copy
long long processShared(const std::shared_ptr<std::vector<int>>& src) {
long long sum = 0;
for (int iter = 0; iter < kLoopCount; ++iter) {
std::shared_ptr<std::vector<int>> local = src;
for (int x : *local) sum += x;
}
return sum;
}
long long result = processShared(SHARED_DATA); Raw Ptr Cached
long long processRaw(const std::shared_ptr<std::vector<int>>& src) {
long long sum = 0;
for (int iter = 0; iter < kLoopCount; ++iter)
for (int x : *src) sum += x;
return sum;
}
long long result = processRaw(SHARED_DATA); Shared test data (shared-setup)
constexpr int kDataSize = 16;
constexpr int kLoopCount = 16;
static std::shared_ptr<std::vector<int>> makeData() {
auto v = std::make_shared<std::vector<int>>(kDataSize);
std::iota(v->begin(), v->end(), 1);
return v;
}
static const std::shared_ptr<std::vector<int>> SHARED_DATA = makeData(); Which snippet is faster?
Snippet B is faster. With this smaller dataset, the shared_ptr reference count increment/decrement in snippet A becomes a larger fraction of total work, while snippet B reuses the same shared_ptr handle without creating per-iteration ownership copies.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Raw Ptr Cached | 51.9 ns | 1.4× |
| Shared Ptr Loop Copy | 71.2 ns | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.