Copy vs Move Semantics: std::string Performance
Question 11 / 12 • Correct so far: 0 (0 answered)
Snippet A
String Copy
std::string processString(std::string data) {
std::string result = data;
result += " processed";
return result;
}
std::string input = TEST_INPUT;
std::string output = processString(input); Snippet B
String Move
std::string processString(std::string data) {
std::string result = std::move(data);
result += " processed";
return result;
}
std::string input = TEST_INPUT;
std::string output = processString(std::move(input)); Shared test data (shared-setup)
const std::string TEST_INPUT = "Hello, World! This is a test string with some content."; Which snippet is faster?
Snippet B is faster then A because it can move the ownership
of the string, while A requires copy/allocation cost.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| String Copy | 42.1 ns | 1.0× |
| String Move | 23 ns | 1.8× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.