Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Destitute-Streetdwelling-Guttersnipe/5429679c66bbc06cef2b93527296f1a8 to your computer and use it in GitHub Desktop.
Save Destitute-Streetdwelling-Guttersnipe/5429679c66bbc06cef2b93527296f1a8 to your computer and use it in GitHub Desktop.
Short / Small String Optimization (SSO) implementations in std::string

Short / Small String Optimization (SSO) implementations in std::string

Short / Small String Optimization (SSO) is a technique to improve performance when working with short strings.

Here are the internals of std::string in popular standard libraries:

MSVC STL (popular in Windows)

- at 0x00 int64       dataPtr
- at 0x00 byte[16]    inlineData (max length = 15)
- at 0x10 int64       length
- at 0x18 int64       capacity (0x0F means inlineString)

GCC libstdc++ (popular in *nix)

- at 0x00 int64       dataPtr
- at 0x08 int64       length (0 to 0x0F means inlineData)
- at 0x10 byte[16]    inlineData (max length = 15)
- at 0x10 int64       capacity (if not inlineData)

LLVM libc++ (popular in MacOS)

- at 0x00 int64       capacity (LSB=1 if not inlineData)
- at 0x00 byte        length (=strlen(inlineData)*2)
- at 0x01 byte[23]    inlineData (max length = 22)
- at 0x08 int64       length (if not inlineData)
- at 0x10 int64       dataPtr (if not inlineData)

More reading

Memory Layout of std::string https://tastycode.dev/memory-layout-of-std-string/

Inside STL: The string - The Old New Thing https://devblogs.microsoft.com/oldnewthing/20230803-00/?p=108532

Libc++'s Implementation of std::string | Hacker News https://news.ycombinator.com/item?id=22198158

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment