Range-based for loop: copy vs reference
Question 12 / 17 • Correct so far: 0 (0 answered)
Range For Copy
void processStrings(const std::vector<std::string>& strings) {
for (auto item : strings) {
benchmark::DoNotOptimize(item.size());
}
} Range For Ref
void processStrings(const std::vector<std::string>& strings) {
for (const auto& item : strings) {
benchmark::DoNotOptimize(item.size());
}
} Shared test data (shared-setup)
static std::vector<std::string> createStringVector() {
std::vector<std::string> strings;
for (int i = 0; i < 1000; ++i) {
strings.push_back("string_" + std::to_string(i));
}
return strings;
} Which snippet is faster?
Reference binding avoids copying each element. With copy semantics, every iteration performs a full copy of the element (string, in this case), which is expensive for large objects. Reference binding accesses the original element in-place, eliminating the copy overhead entirely.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Range For Copy | 2.46 us | 1.0× |
| Range For Ref | 192 ns | 12.8× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.