stl · medium
Small String Optimization (SSO)
std::string uses Small String Optimization: short strings are stored in an inline buffer inside the object, so common short strings cost zero allocations and stay cache-friendly. Once the string exceeds the inline capacity (~15 chars typically), it allocates a heap buffer and the object reinterprets its storage as {pointer, size, capacity}. sizeof(std::string) is fixed either way.
🔑 Key line
Small String Optimization: a std::string keeps short strings (~15 chars) inside the object itself — no heap. Longer strings allocate on the heap; sizeof(std::string) never changes.
The code
std::string s; // empty: cap ~15, no heaps = "hi"; // 2 chars: lives INLINEs = "exactly_15_char"; // 15 chars: still inline (at limit)s = "long enough to overflow"; // > 15 chars: HEAP allocation// now: s.data() points to the heap; sizeof(s) is unchangedWhat this lesson walks through
- 01
- 02
- 03
- 04
- 05
- 06
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Small String Optimization (SSO) and 100+ animated C++ interview lessons.