Sub topic 3
How Strings Sit in Memory
This chapter assumes you can read basic Python, know what an array is, and understand Big-O notation. It also assumes you know that a code point is a number assigned to a character, and that UTF-8 turns code points into bytes.
Strings are blocks of bytes
Memory is a long row of numbered byte slots. A string occupies a contiguous run of those slots, like an array. The string's data starts at one address, and each element sits at a fixed distance from the start.
Contiguous storage has two consequences:
- Finding element
iis one multiplication and one addition:start + i * element_size. That is O(1). - The string's size must be known or discoverable, because nothing in memory marks where the run ends.
The second point leads to two classic designs.
Null-terminated vs length-prefixed
A null-terminated string (C style) stores the bytes followed by a zero byte. Code finds the end by scanning for that zero. A length-prefixed string stores the byte count next to the data, so the length is read directly.
| Property | Null-terminated | Length-prefixed |
|---|---|---|
| Get length | O(n), scan to the zero byte | O(1), read the stored number |
| Can contain a zero byte | No, it would end the string early | Yes |
| Extra space | 1 byte | 4 or 8 bytes typical |
| Cutting off the end | Write a zero | Change the length |
The following code shows both ideas with raw bytes:
import struct
payload = b"hi\x00there"
# Null-terminated reading stops at the first zero byte
c_style = payload.split(b"\x00")[0]
print(c_style) # b'hi'
print(len(payload)) # 8, the real number of bytes
# Length-prefixed: a 4-byte little-endian length, then the data
packed = struct.pack("<I", len(payload)) + payload
(length,) = struct.unpack_from("<I", packed)
print(length) # 8
print(packed[4:4 + length]) # b'hi\x00there'The null-terminated reading loses there. Length-prefixing keeps all eight bytes. Most modern languages, including Python, Java, Go, and Rust, store a length with the data.
Element size depends on the encoding
How many bytes does each "position" take? That depends on the encoding.
- Fixed width encodings such as ASCII, Latin-1, or UTF-32 use the same number of bytes per code point. Indexing stays O(1).
- Variable width encodings such as UTF-8 use 1 to 4 bytes per code point. Byte
iis easy to reach, but code pointirequires scanning from the start.
UTF-16 is also variable width. Characters outside the first 65,536 code points use two 16-bit units, called a surrogate pair.
Languages choose different trade-offs:
- Rust and Go store UTF-8 bytes. Their indexing is by byte, which is fast and compact. Rust refuses to slice in the middle of a character.
- Java and JavaScript use UTF-16 code units, so
lengthcounts units, not characters. - Python 3 picks a fixed width per string. It uses the smallest width that fits the largest code point in that string (PEP 393, "flexible string representation"). The next example measures this.
import sys
def bytes_per_char(ch):
big = sys.getsizeof(ch * 2000)
small = sys.getsizeof(ch * 1000)
return (big - small) // 1000
print(bytes_per_char("a")) # 1 (ASCII)
print(bytes_per_char("é")) # 1 (code point below 256)
print(bytes_per_char("€")) # 2 (needs 16 bits)
print(bytes_per_char("😀")) # 4 (needs 32 bits)The exact header size varies between Python versions, which is why the code compares two sizes. The difference per character is stable. One emoji in a long text makes every character in that string take 4 bytes.
Where the characters live
In most languages, a string variable holds a reference (a pointer) to a separate heap block. That block has a header (reference count, length, cached hash, encoding flags) followed by the character data. This has three effects:
- Copying a variable copies a pointer, not the text.
- Every string pays a fixed overhead. Many tiny strings use far more memory than their characters suggest.
- Reading a long string sequentially is fast, because contiguous bytes fit well in CPU caches.
Some implementations store short strings inside the object itself, so no second allocation is needed. This is called small-string optimization, and C++ standard libraries commonly use it. Others share one buffer between a string and its slices. Go and older Java versions did this, and it can keep a large buffer alive because of a small slice.
Common errors
- Assuming
lengives the byte count when the data may include non-ASCII text. - Using a null-terminated approach with data that can contain zero bytes, such as binary protocols.
- Slicing a UTF-8 byte string at an arbitrary byte, which can split a character and produce invalid text.
Exercise
A language stores strings as UTF-8 bytes with a length prefix. Why is length_in_bytes O(1) but finding the 1000th character O(n)?
Show answer
The prefix holds the byte count, so reading it is one lookup. Characters take 1 to 4 bytes in UTF-8, so the position of the 1000th character is unknown without scanning from the start and counting character boundaries.