Programming Search⌘K

Conceptcore

How strings are stored

Also called string representation, string layout, null-terminated string, length-prefixed string, Pascal string, small string optimization, SSO, compact strings.

A string is stored as a block of code units with a terminator or a stored length. The encoding of the units and the small string optimization change its size and speed.

Applies to
core-languages

Idea

A string is text, but in memory it is a block of numbers. The program must know two things about the block: where it ends, and how each number maps to a character. C marks the end with a byte of value zero. Most other languages store the length next to the characters. For the second question, each runtime picks an encoding: bytes of UTF-8, 16-bit units of UTF-16, or a width that fits the widest character of the string.

import sys

# CPython stores each string with 1, 2 or 4 bytes per code point (PEP 393).
# The widest code point in the string decides the width.
for ch in ["a", "é", "€", "😀"]:
    per_char = sys.getsizeof(ch * 101) - sys.getsizeof(ch * 100)
    print(f"U+{ord(ch):04X} {per_char} byte(s) per code point")

# One wide code point makes the whole string wide.
narrow = "a" * 1000
wide = "a" * 999 + "😀"
print(len(narrow), len(wide), sys.getsizeof(wide) - sys.getsizeof(narrow) > 2000)
Output
U+0061 1 byte(s) per code point
U+00E9 1 byte(s) per code point
U+20AC 2 byte(s) per code point
U+1F600 4 byte(s) per code point
1000 1000 True

Each extra character adds 1 byte when all code points are below U+0100, 2 bytes when one of them needs 16 bits, and 4 bytes when one is above U+FFFF. Both long strings have 1000 code points. But one emoji makes CPython store all 1000 of them in 4 bytes each, so the second string takes about 3000 bytes more than the first.

How it works

The end of the string. There are two main layouts.

  • A terminator. "A null-terminated byte string (NTBS) is a sequence of nonzero bytes followed by a byte with value zero (the terminating null character)"1. Wikipedia notes that "This representation of an n-character string takes n + 1 space"2. The cost is that strlen must scan every byte to find the length, and that the string cannot contain a byte of value zero.
  • A stored length. "The length of a string can also be stored explicitly, for example by prefixing the string with the length as a byte value"2. Many Pascal dialects did this, and "Storing the string length as byte limits the maximum string length to 255"2. Modern runtimes store the length in a full machine word.

A header and a buffer. Most languages keep a small fixed-size header and put the characters in a buffer on the heap.

  • Go describes its string header as a structure with the fields Data uintptr and Len int, and says that "StringHeader is the runtime representation of a string"3. The header has no capacity, because a Go string cannot grow. unsafe.StringData "returns a pointer to the underlying bytes of str"4.
  • In Rust, "A String is made up of three components: a pointer to some bytes, a length, and a capacity", and "This buffer is always stored on the heap"5. A &str has only the pointer and the length.
  • A C++ std::string stores its characters contiguously, and "*(s.begin() + s.size()) has value CharT() (a null terminator)"6. So it has both a stored length and a terminator, and c_str() can give the buffer to a C function with no copy.
  • In .NET, "a String object can include embedded null characters, which count as a part of the string's length"7.

Slices. A header with a pointer and a length can point into the middle of another string's buffer. Go substrings and Rust &str slices work this way, so a substring costs no copy. The slice keeps the whole buffer alive, so a small substring of a large string can hold a lot of memory.

The encoding of the units. The encoding decides how many bytes each character takes.

  • UTF-8. Go, Rust and C++ std::string usually hold UTF-8, where a code point takes 1 to 4 bytes. Swift also uses it: "Swift 5 switches the preferred encoding of strings from UTF-16 to UTF-8 while preserving efficient Objective-C-interoperability"8.
  • UTF-16. "A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs"9 in Java, and JavaScript "Strings are represented fundamentally as sequences of UTF-16 code units"10. C# works in the same way. A code point takes 2 or 4 bytes.
  • A width per string. With PEP 393, the CPython string type has "multiple internal representations, depending on the character with the largest Unicode ordinal (1, 2, or 4 bytes)"11. So the index of a code point is still O(1), but one wide character makes the whole string wide.
  • Latin-1 when possible. Java's compact strings store "characters encoded either as ISO-8859-1/Latin-1 (one byte per character), or as UTF-16 (two bytes per character), based upon the contents of the string"12. The reason was that "most String objects contain only Latin-1 characters"12. The API still shows UTF-16, so length() and charAt do not change.

The small string optimization. Many strings are short: names, keys and words. A C++ library can keep the characters of a short string inside the string object, so it needs no heap allocation. Raymond Chen explains that "the small string optimization means that an empty string can be created without any heap allocations"13. The three main C++ libraries differ. For gcc, the internal buffer "holds as many characters as fit into 16 bytes (minus 1, for the null terminator)"13. The Microsoft library also uses 16 bytes. The clang library uses one bit to tell the two layouts apart, which "lets clang shrink a std::string down to 24 bytes on 64-bit systems, while still allowing 8-bit strings up to 22 characters and 16-bit strings up to 10 characters to be treated as short"13. Swift small strings also "pack their contents directly in the String struct"8, so they need no allocation.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeTypeScript compiles to JavaScript, so its strings have the JavaScript layout of UTF-16 code units, and the types do not change the representation. No example file exists.
GoNative
RustNative
KotlinNativeOn the JVM a Kotlin String is a java.lang.String, so it has the same layout, with compact Latin-1 storage when the text allows it. No example file exists because kotlinc is not installed.
SQLNativeEach database has its own storage. CHAR(n) pads the value to n characters, and VARCHAR(n) stores a length with the characters, in the character set of the column. No example file exists.
BashNativeBash keeps the value of a variable as a C string, so a variable cannot hold a null byte, and the length in characters depends on the locale. No example file exists.
PowerShellNativePowerShell strings are .NET System.String objects, with a stored length and UTF-16 code units. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is text. A browser stores the text of the document in DOM strings, which are sequences of UTF-16 code units.
CSSDoes not applyA stylesheet is text, and the browser engine decides how to store its strings.
Regular expressionsDoes not applyA regex engine reads the strings of its host language and has no storage of its own.
Language Verdict Mechanism
Python native object header, stored length, 1, 2 or 4 bytes per code point (PEP 393)
JavaScript native UTF-16 code units in the language; the engine chooses the internal layout
TypeScript native the JavaScript layout; types do not change the representation
Java native byte[] with a coder flag: Latin-1 or UTF-16 (compact strings)
Kotlin native java.lang.String on the JVM, with the same compact layout
C# native object with a stored length and UTF-16 char values; null characters allowed inside
Go native header of pointer and length, 16 bytes on 64-bit systems; UTF-8 bytes; substrings share bytes
Rust native String: pointer, capacity and length; &str: pointer and length; UTF-8 bytes
C idiom char array that ends with a null byte; the length is not stored
C++ stdlib std::string: stored size, capacity and a null terminator; small string optimization
Bash native C strings inside the shell, so a variable cannot hold a null byte
PowerShell native the .NET System.String layout
SQL native each database has its own layout: fixed CHAR(n) with padding and VARCHAR(n) with a length
Regex n/a a regex engine reads the strings of its host language
HTML n/a the browser stores text nodes as DOM strings, which are UTF-16
CSS n/a the stylesheet is text, and the engine decides the storage

The languages fall into three groups. C keeps no length. Go, Rust and C++ keep a length in a small header and UTF-8 bytes in a buffer. Java, JavaScript and C# keep UTF-16 code units, and Java and CPython save memory with a narrower width when the text allows it.

The example files make the layouts visible. Python compares the size of one text in Latin-1, UTF-8, UTF-16 and UTF-32, and shows a null character inside a str. JavaScript shows a surrogate pair and a lone surrogate that is not well-formed text. Java and C# count the bytes of each encoding and store a null char in a string. Go shows the 16-byte header and a substring that shares the bytes of its parent. Rust shows the sizes of String, &str and Box<str>, the capacity, and a slice at an offset in the same buffer. C compares a null-terminated array with a length-prefixed structure. C++ finds the characters of a short string inside the object and those of a long string outside it.

PythonGitHub
import sys

# The same text takes a different number of bytes in each encoding.
for text in ["hello", "café", "日本", "😀"]:
    sizes = []
    for enc in ["latin-1", "utf-8", "utf-16-le", "utf-32-le"]:
        try:
            sizes.append(str(len(text.encode(enc))))
        except UnicodeEncodeError:
            sizes.append("-")
    print(f"{text!r}: latin-1={sizes[0]} utf-8={sizes[1]} utf-16={sizes[2]} utf-32={sizes[3]}")

# A Python string stores its length, so a null character is an ordinary character.
s = "a\0b"
print(len(s), s.encode("ascii"))

# A slice of a str is a new string with its own storage.
big = "x" * 10_000
part = big[:10]
print(sys.getsizeof(part) < sys.getsizeof(big))
Output
'hello': latin-1=5 utf-8=5 utf-16=10 utf-32=20
'café': latin-1=4 utf-8=5 utf-16=8 utf-32=16
'日本': latin-1=- utf-8=6 utf-16=4 utf-32=8
'😀': latin-1=- utf-8=4 utf-16=4 utf-32=4
3 b'a\x00b'
True
  • Verdict: native. The same text takes a different number of bytes in each encoding, and Latin-1 cannot encode 日本 or the emoji. A str stores its length, so "a\0b" has 3 characters and the null character is ordinary data. A slice is a new string with its own storage, so it is much smaller than the string it came from.
#include <iostream>
#include <string>
#include <string_view>

// is_inline reports whether the characters are inside the string object,
// which is the small string optimization.
bool is_inline(const std::string& s) {
    const char* object = reinterpret_cast<const char*>(&s);
    return s.data() >= object && s.data() < object + sizeof s;
}

int main() {
    std::string small = "hi";
    std::string large(100, 'x');
    std::cout << std::boolalpha;
    std::cout << "small inline: " << is_inline(small) << '\n';
    std::cout << "large inline: " << is_inline(large) << '\n';

    // An empty string already has room for some characters without allocation.
    std::string empty;
    std::cout << "empty capacity >= 15: " << (empty.capacity() >= 15) << '\n';

    // A std::string_view is a pointer and a length into other memory.
    std::string_view view(large.data() + 10, 5);
    std::cout << view << ' ' << (view.data() == large.data() + 10) << '\n';

    // The characters are contiguous and a null character follows them.
    std::cout << (large.data()[large.size()] == '\0') << '\n';
}
Output
small inline: true
large inline: false
empty capacity >= 15: true
xxxxx true
true
  • Verdict: stdlib. The characters of the short string "hi" are inside the std::string object, which is the small string optimization. The 100 characters of large are in a heap buffer. An empty string has room for at least 15 characters with no allocation. A std::string_view points into the buffer of large, and a null character follows the last character.
JavaGitHub
import java.nio.charset.StandardCharsets;

public class Main {
  public static void main(String[] args) {
    // The same text in three encodings. Latin-1 cannot hold every character.
    for (String text : new String[] {"hello", "café", "日本", "😀"}) {
      boolean latin1 = StandardCharsets.ISO_8859_1.newEncoder().canEncode(text);
      System.out.printf("%s: chars=%d latin-1=%s utf-8=%d utf-16=%d%n",
          text, text.length(),
          latin1 ? String.valueOf(text.getBytes(StandardCharsets.ISO_8859_1).length) : "-",
          text.getBytes(StandardCharsets.UTF_8).length,
          text.getBytes(StandardCharsets.UTF_16LE).length);
    }

    // A String stores its length, so a null char is an ordinary char.
    String s = "a\0b";
    System.out.println(s.length() + " " + (int) s.charAt(1));

    // A lone surrogate is a valid String but not valid text.
    // getBytes replaces it with '?' (63).
    String lone = "😀".substring(0, 1);
    byte[] bytes = lone.getBytes(StandardCharsets.UTF_8);
    System.out.println(lone.length() + " " + bytes.length + " " + bytes[0]);
  }
}
Output
hello: chars=5 latin-1=5 utf-8=5 utf-16=10
café: chars=4 latin-1=4 utf-8=5 utf-16=8
日本: chars=2 latin-1=- utf-8=6 utf-16=4
😀: chars=2 latin-1=- utf-8=4 utf-16=4
3 0
1 1 63
  • Verdict: native. length() counts UTF-16 char values, and the byte counts show the size in Latin-1, UTF-8 and UTF-16. Latin-1 can encode hello and café, which are the strings that compact strings store with one byte per character. A String stores its length, so a null char is data. A lone surrogate encodes to one ? byte (63).
#include <stdio.h>
#include <string.h>

/* A length-prefixed string, as in Pascal: the length comes first. */
struct pstring {
    unsigned char len;
    char data[255];
};

int main(void) {
    /* A null-terminated string: the bytes, then a byte with value zero. */
    char c_str[] = "hello";
    printf("strlen=%zu sizeof=%zu last=%d\n", strlen(c_str), sizeof c_str, c_str[5]);

    /* strlen must scan to the null byte. A stored length is read at once. */
    struct pstring p = {5, "hello"};
    printf("pstring len=%d max=%zu\n", p.len, sizeof p.data);

    /* A null byte inside the data ends a C string early. */
    char data[] = {'a', 'b', '\0', 'c', 'd', '\0'};
    printf("strlen=%zu sizeof=%zu\n", strlen(data), sizeof data);

    /* A pointer and a length make a slice without a null byte. */
    const char *text = "hello, world";
    const char *start = text + 7;
    int n = 5;
    printf("%.*s\n", n, start);
    return 0;
}
Output
strlen=5 sizeof=6 last=0
pstring len=5 max=255
strlen=2 sizeof=6
world
  • Verdict: idiom. The array "hello" takes 6 bytes, because the null byte follows the 5 characters. A length-prefixed structure keeps the length in its first byte, so a program reads it at once but the string can have at most 255 characters. A null byte inside the data makes strlen stop at 2. A pointer and a length give a slice, and %.*s prints it without a null byte.
using System.Text;

// A char is one UTF-16 code unit of 2 bytes.
Console.WriteLine(sizeof(char));

// The same text in three encodings.
foreach (string text in new[] { "hello", "café", "日本", "😀" })
{
    Console.WriteLine($"{text}: chars={text.Length} utf-8={Encoding.UTF8.GetByteCount(text)} utf-16={Encoding.Unicode.GetByteCount(text)}");
}

// Latin-1 replaces characters that it cannot hold with '?'.
byte[] latin = Encoding.Latin1.GetBytes("café 日本");
Console.WriteLine(Encoding.Latin1.GetString(latin));

// A string stores its length, so it can hold a null character.
string s = "a\0b";
Console.WriteLine($"{s.Length} {(int)s[1]}");
Output
2
hello: chars=5 utf-8=5 utf-16=10
café: chars=4 utf-8=5 utf-16=8
日本: chars=2 utf-8=6 utf-16=4
😀: chars=2 utf-8=4 utf-16=4
café ??
3 0
  • Verdict: native. A char takes 2 bytes, and Length counts UTF-16 code units. GetByteCount gives the size of each text in UTF-8 and UTF-16. Encoding.Latin1 replaces the characters that it cannot hold with ?. A string stores its length, so it can hold a null character.
JavaScriptGitHub
// A JavaScript string is a sequence of UTF-16 code units.
for (const text of ["hello", "café", "日本", "😀"]) {
  const utf8 = new TextEncoder().encode(text).length;
  console.log(`${JSON.stringify(text)}: code units=${text.length} utf-8 bytes=${utf8}`);
}

// The emoji is stored as a surrogate pair: two code units.
const face = "😀";
console.log(face.charCodeAt(0).toString(16), face.charCodeAt(1).toString(16));

// A string can hold a lone surrogate, which is not valid UTF-16 text.
const lone = face.slice(0, 1);
console.log(lone.length, lone.isWellFormed(), face.isWellFormed());
try {
  encodeURIComponent(lone);
} catch (e) {
  console.log(e.name);
}
console.log(lone.toWellFormed().codePointAt(0).toString(16));
Output
"hello": code units=5 utf-8 bytes=5
"café": code units=4 utf-8 bytes=5
"日本": code units=2 utf-8 bytes=6
"😀": code units=2 utf-8 bytes=4
d83d de00
1 false true
URIError
fffd
  • Verdict: native. length counts UTF-16 code units, so 日本 is 2 units but 6 UTF-8 bytes, and the emoji is 2 units. charCodeAt shows the surrogate pair d83d de00. A slice can cut the pair in half. The result is a string, but isWellFormed is false and encodeURIComponent throws URIError. toWellFormed replaces the lone surrogate with U+FFFD.
package main

import (
	"fmt"
	"unsafe"
)

func main() {
	// A string value is a pointer to bytes and a length: 16 bytes on a 64-bit system.
	s := "hello, world"
	fmt.Println(unsafe.Sizeof(s), len(s))

	// A substring shares the bytes of the original string. No copy is made.
	sub := s[7:]
	same := unsafe.StringData(sub) == (*byte)(unsafe.Add(unsafe.Pointer(unsafe.StringData(s)), 7))
	fmt.Println(sub, same)

	// A conversion to []byte gives bytes that can change, so the bytes are a copy.
	b := []byte(s)
	b[0] = 'H'
	fmt.Println(string(b), "|", s, unsafe.SliceData(b) == unsafe.StringData(s))

	// The bytes are UTF-8, so non-ASCII text takes more bytes than characters.
	for _, t := range []string{"café", "日本", "😀"} {
		fmt.Printf("%s: bytes=%d % x\n", t, len(t), t)
	}
}
Output
16 12
world true
Hello, world | hello, world false
café: bytes=5 63 61 66 c3 a9
日本: bytes=6 e6 97 a5 e6 9c ac
😀: bytes=4 f0 9f 98 80
  • Verdict: native. A string value is 16 bytes on a 64-bit system: a pointer and a length. The substring s[7:] points 7 bytes into the same memory, so it costs no copy. A []byte that the program changes is a copy, so s stays as it was. The bytes are UTF-8: 5 for café, 6 for 日本 and 4 for the emoji.
RustGitHub
use std::mem::size_of;

fn main() {
    // String is a pointer, a capacity and a length. &str is a pointer and a length.
    println!("{} {} {}", size_of::<String>(), size_of::<&str>(), size_of::<Box<str>>());

    // The capacity can be larger than the length, so a push may not allocate.
    let mut s = String::with_capacity(16);
    s.push_str("hello");
    println!("{} {}", s.len(), s.capacity());

    // A slice points into the same buffer. It copies nothing.
    let world = String::from("hello, world");
    let part: &str = &world[7..];
    let offset = part.as_ptr() as usize - world.as_ptr() as usize;
    println!("{part} {offset}");

    // The buffer holds UTF-8 bytes.
    for t in ["café", "日本", "😀"] {
        println!("{t}: bytes={} {:02x?}", t.len(), t.as_bytes());
    }
}
Output
24 16 16
5 16
world 7
café: bytes=5 [63, 61, 66, c3, a9]
日本: bytes=6 [e6, 97, a5, e6, 9c, ac]
😀: bytes=4 [f0, 9f, 98, 80]
  • Verdict: native. String is 24 bytes (pointer, capacity and length), and &str and Box<str> are 16 bytes (pointer and length). with_capacity(16) makes room before the push, so the capacity is larger than the length. The slice &world[7..] points 7 bytes into the same buffer. as_bytes shows the UTF-8 bytes.
  • Ropes. A rope stores a long string as a tree of pieces, so that an insertion or a concatenation does not copy the whole text.
  • Interning. A runtime can keep one copy of each equal string constant, so that many references share it.
  • Copy on write. A mutable string can share its buffer with a copy until one of the two changes. Then the string that changes makes its own copy of the buffer.
  • UTF-32. A fixed width of 4 bytes makes the index of a code point O(1) but uses the most memory.
  • Wide strings in C and C++. The size of wchar_t depends on the platform. "In practice, it is 32 bits and holds UTF-32 on Linux and many other non-Windows systems, but 16 bits and holds UTF-16 code units on Windows"14. So the same code stores text in different ways.

Pitfalls

  • strlen in a loop condition. for (i = 0; i < strlen(s); i++) scans the whole string on each pass, so the loop is O(n²). Compute the length once.
  • A null byte in binary data. C string functions stop at the first null byte. Data from a file can contain one, so keep a separate length.
  • A small slice of a large string. In Go and Rust, a slice keeps the whole buffer alive. Copy the slice with strings.Clone or to_owned when you keep it for a long time.
  • Size estimates that assume one byte per character. A buffer for N characters in UTF-8 needs up to 4N bytes. In UTF-16 a character outside the Basic Multilingual Plane needs 2 code units.
  • Lone surrogates. A UTF-16 string can hold half of a surrogate pair. It is a valid JavaScript or Java string, but it is not valid text, and an encoder replaces it or fails.
  • Assumptions about object size. The size of a std::string and the length of its inline buffer differ between C++ libraries, so code must not depend on them.

Cost

The length is O(1) to read when the layout stores it, and O(n) for a C string. A header with a pointer adds one indirection to each access and one heap allocation to each new string, unless the string is small enough for an inline buffer. A fixed-width encoding gives O(1) access by index. UTF-8 and UTF-16 give O(1) access by code unit but O(n) access by code point. The memory cost of N characters is about N bytes for Latin-1 or ASCII text in UTF-8, Java compact strings or CPython, 2N bytes for UTF-16, and 4N bytes for UTF-32 or a CPython string with an emoji in it.

History

Null-terminated strings are older than C. They "were produced by the .ASCIZ directive of the PDP-11 assembly languages and the ASCIZ directive of the MACRO-10 macro assembly language for the PDP-10"15. "C designer Dennis Ritchie chose to follow the convention of null-termination to avoid the limitation on the length of a string and because maintaining the count seemed, in his experience, less convenient than using a terminator"15. The choice spread with C, "a convention used and perpetuated by the popular C programming language"2. Pascal dialects used a length byte, and later versions of length-prefixed strings "use 16-, 32-, or 64-bit words to store the string length"2.

Later runtimes tuned their layout for memory. PEP 393 (Python 3.3) gave CPython "a space-efficient representation in common cases"11. JEP 254 (Java 9) took the same path for Java, because "strings are a major component of heap usage"12. In 2019 Swift moved from UTF-16 to UTF-8 storage. Before that change, "string content could be in one of two native storage encodings: UTF-16 for Unicode-rich text, and a dedicated ASCII storage class when contents are all ASCII"8.

References

  1. Null-terminated byte strings, C reference, cppreference.com, Introduction
  2. String (computer science), Wikipedia, Representations; Null-terminated; Length-prefixed
  3. Package reflect, Go standard library, type StringHeader
  4. Package unsafe, Go standard library, func StringData
  5. Struct String, The Rust Standard Library, Representation
  6. std::basic_string, C++ reference, cppreference.com, Introduction
  7. String Class, .NET API reference, Remarks, Embedded null characters
  8. Michael Ilseman, UTF-8 String, Swift.org blog (2019), Introduction; Unified Storage Representation
  9. Class String, Java SE 25 API, Class description
  10. String, MDN Web Docs, UTF-16 characters, Unicode code points, and grapheme clusters
  11. PEP 393, Flexible String Representation, Abstract; Specification
  12. JEP 254, Compact Strings, Summary; Motivation; Description
  13. Raymond Chen, Inside STL, The string, The Old New Thing (2023), The small string optimization; the gcc, Microsoft and clang layouts
  14. Fundamental types, C++ reference, cppreference.com, Character types, wchar_t
  15. Null-terminated string, Wikipedia, History

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/P3D8VD/text.yaml