Table of Contents

C++ Small string optimization

Small string optimization (SSO) is a technique where std::string stores short strings directly in its object rather than allocating from the heap. This eliminates heap allocation overhead for short strings (typically up to 15-24 bytes depending on the implementation) while keeping the std::string object size constant.

Rely on SSO implicitly through standard library implementations; don't write code assuming specific SSO buffer sizes.

Example

This example shows how SSO improves performance for short strings.

// compile: g++ -o sso sso.cpp
// run: ./sso
// description: small string optimization avoids heap allocation for short strings
 
#include <iostream>
#include <string>
#include <chrono>
 
int main() {
    std::cout << "sizeof(std::string): " << sizeof(std::string) << "\n";
 
    // Short string (likely SSO): no heap allocation
    std::string short_str = "hi";
 
    // Longer string: heap allocation
    std::string long_str = "this is a much longer string that exceeds SSO buffer";
 
    // Both work the same way; SSO is transparent
    std::cout << "Short: " << short_str << "\n";
    std::cout << "Long: " << long_str << "\n";
 
    return 0;
}