@ 261106.4raw
current

Strings in V8

Strings are a fundamental data type in JavaScript, and V8 uses a complex hierarchy of string representations to optimize various operations like concatenation, slicing, and internalization.

String Representation Hierarchy

All strings in V8 inherit from the String class (defined in src/objects/string.h). V8 uses different concrete classes depending on how the string was created and how it is used.

1. Sequential Strings (SeqString)

Captures sequential string values where the characters are stored directly in the object.

2. Cons Strings (ConsString)

Describes string values built by using the addition operator (+) on strings.

3. Sliced Strings (SlicedString)

Describes strings that are substrings of another sequential string.

4. Thin Strings (ThinString)

Describes string objects that are just references to another string object.

5. External Strings (ExternalString)

Describes string values that are backed by a string resource that lies outside the V8 heap (e.g., in the embedder like Chrome or Node.js).

String Transitions and Internalization

Internalization

When a string is used as a property key (e.g., obj["prop"]), V8 internalizes it. This means it ensures there is only one unique instance of that string value in the String Table (a hash table).

Flattening

As mentioned above, ConsString instances are tree structures. To read characters efficiently or pass them to APIs that expect flat buffers, V8 will flatten the tree into a single SeqString.

String Instance Types and Bitfield

V8 uses the InstanceType field in the object Map to identify the specific representation and encoding of a string. For strings, the high-order bits (bits 7-15) are cleared, and the lower bits form a bitfield:

This bitfield layout allows V8 to perform extremely fast checks (e.g., checking if a string is one-byte or internalized) using simple bitwise operations.

The String Table

The String Table is a hash table that stores all internalized strings.

How it Works

Thread Safety

File Structure