Atoms Overview
Atoms are an important concept in QuickJS for efficient string handling, particularly for property names and identifiers. Understanding atoms is crucial for writing efficient C extensions.What Are Atoms?
An atom in QuickJS is an interned string identifier represented by a 32-bit integer (JSAtom). Atoms are used throughout the QuickJS engine to represent:
- Object property names
- Variable identifiers
- Function names
- Symbol descriptions
Type Definition
Why Use Atoms?
1. Performance
String comparison is an O(n) operation where n is the length of the string. Atom comparison is O(1) since it’s just an integer comparison.2. Memory Efficiency
When the same string is used multiple times (like property names), atoms ensure only one copy exists in memory. All references use the same atom ID.3. Standardization
The QuickJS API requires atoms for property access functions, making them a standard part of the API.Null Atom
The special valueJS_ATOM_NULL represents an invalid or uninitialized atom:
Common Use Cases
Object Property Access
Atoms are primarily used when working with object properties:Property Definition
Repeated Property Access
If you access the same property multiple times, create the atom once and reuse it:Symbol Property Access
Atoms are also used for symbol-keyed properties:Atom Lifecycle
Atoms use reference counting for memory management:- Creation: When you create an atom, its reference count is 1
- Duplication:
JS_DupAtom()increments the reference count - Freeing:
JS_FreeAtom()decrements the reference count - Deletion: When the reference count reaches 0, the atom is removed from the intern table
Atoms vs. Strings
| Aspect | Atoms | Strings |
|---|---|---|
| Type | JSAtom (uint32_t) | JSValue |
| Size | 4 bytes | 16+ bytes |
| Comparison | O(1) integer compare | O(n) string compare |
| Use case | Property names, identifiers | Text values, output |
| Lifecycle | Manual reference counting | Garbage collected |
| Creation | JS_NewAtom() | JS_NewString() |
When to Use Atoms
Use atoms when:- Accessing object properties
- Defining properties on objects
- Working with property enumeration
- Comparing identifiers repeatedly
- Performance is critical
- Displaying text to users
- Returning string values from functions
- Working with arbitrary text content
- The value is not used as a property key
Performance Tips
-
Cache atoms for frequently used property names:
-
Convert between atoms and strings only when needed:
-
Use string-based property functions for one-off access:
See Also
- Atom Operations - Creating, converting, and freeing atoms