std::string: Short String Optimisation Buffer
Question 34 / 51 • Correct so far: 0 (0 answered)
Sso
std::string processShort(const char* src) {
std::string s = src;
s += '!';
return s;
}
std::string result = processShort(SHORT_STR); Heap
std::string processLong(const char* src) {
std::string s = src;
s += '!';
return s;
}
std::string result = processLong(LONG_STR); Shared test data (shared-setup)
static const char SHORT_STR[] = "Hello, World!!";
static const char LONG_STR[] = "Hello, World! This is longer.!"; Which snippet is faster?
Snippet A is faster. Most standard library implementations store strings up to ~15 characters in an internal buffer inside the std::string object (SSO), with no heap allocation. Snippet B's 32-character string exceeds that threshold, so every construction and destruction goes through the allocator.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Heap | 21.7 ns | 1.0× |
| Sso | 4.99 ns | 4.3× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.