String Building: Two Concatenation Styles
Question 42 / 51 • Correct so far: 0 (0 answered)
String Plus
std::string buildString(const std::vector<std::string>& fragments) {
std::string result;
for (const auto& frag : fragments)
result = result + frag;
return result;
}
std::string s = buildString(FRAGMENTS); String Plus Eq
std::string buildString(const std::vector<std::string>& fragments) {
std::string result;
for (const auto& frag : fragments)
result += frag;
return result;
}
std::string s = buildString(FRAGMENTS); Shared test data (shared-setup)
static const std::vector<std::string> FRAGMENTS = []() {
std::vector<std::string> v;
for (int i = 0; i < 200; ++i)
v.push_back("fragment" + std::to_string(i) + "_");
return v;
}(); Which snippet is faster?
Snippet B is faster. s = s + frag repeatedly creates temporaries and
recopies the growing string, while s += frag appends in place when
capacity allows. That usually means much less allocation and copying.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| String Plus | 6.19 us | 1.0× |
| String Plus Eq | 832 ns | 7.4× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.