Lambda Capture: Value Capture vs Reference Capture
Question 4 / 51 • Correct so far: 0 (0 answered)
Capture By Value
std::size_t processOnce(const std::vector<std::string>& data) {
auto fn = [data]() {
std::size_t total = 0;
for (const auto& s : data) total += s.size();
return total;
};
return fn();
}
std::size_t result = processOnce(STRINGS); Capture By Ref
std::size_t processOnce(const std::vector<std::string>& data) {
auto fn = [&data]() {
std::size_t total = 0;
for (const auto& s : data) total += s.size();
return total;
};
return fn();
}
std::size_t result = processOnce(STRINGS); Shared test data (shared-setup)
static const std::vector<std::string> STRINGS = []() {
std::vector<std::string> v;
v.reserve(512);
for (int i = 0; i < 512; ++i)
v.push_back("item_" + std::to_string(i) + "_data");
return v;
}(); Which snippet is faster?
Snippet B is faster. Capturing by value copies the full container when the lambda is created. Capturing by reference avoids that copy, so repeated lambda creation costs much less.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Capture By Ref | 79.7 ns | 19.3× |
| Capture By Value | 1.54 us | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.