Skip to main content

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
By using atoms instead of raw strings, QuickJS can perform fast pointer or integer comparisons instead of expensive string comparisons.

Type Definition

Atoms are simple 32-bit unsigned integers that serve as handles to interned strings.

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 value JS_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:
  1. Creation: When you create an atom, its reference count is 1
  2. Duplication: JS_DupAtom() increments the reference count
  3. Freeing: JS_FreeAtom() decrements the reference count
  4. Deletion: When the reference count reaches 0, the atom is removed from the intern table

Atoms vs. Strings

When to Use Atoms

Use atoms when:
  • Accessing object properties
  • Defining properties on objects
  • Working with property enumeration
  • Comparing identifiers repeatedly
  • Performance is critical
Use strings when:
  • 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

  1. Cache atoms for frequently used property names:
  2. Convert between atoms and strings only when needed:
  3. Use string-based property functions for one-off access:

See Also