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 heap
s = "hi"; // 2 chars: lives INLINE
s = "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 unchanged

What this lesson walks through

  1. 01
  2. 02
  3. 03
  4. 04
  5. 05
  6. 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.

← Previous
std::variant & std::visit
Next →
std::optional