6.5 ALTREP and Deferred Representation

R RUNTIMESTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18

6.5.1 Motivation

The R statement 1:1e9 creates a sequence of one billion integers, yet it allocates almost nothing. A plain integer vector of that length would need 4 GB. R stores only the length, the first value and the step, and computes an element when code asks for one, so x[500000000] is worked out on the spot. This is ALTREP: an alternative representation that defers work and saves space.

To R code, an ALTREP vector behaves like an ordinary atomic vector, but its data lives in a compact form. When C code asks for a pointer to the full data, the vector materializes: R allocates an ordinary array, fills it from the compact form, and stores it inside the ALTREP object. That store is a write to the object, and it can happen during a read.

6.5.2 Mental model

An ordinary atomic vector keeps its data right after the SEXP header, on R’s heap. A REALSXP vector holds a C double array. An INTSXP vector holds a C int array. If the vector has 1000 elements, the data occupies 1000 times the element size in memory.

An ALTREP vector is a different kind of node. A bit in the header, alt, marks it as ALTREP. The node’s three pointer slots, which a pairlist cell uses for CAR, CDR and TAG, hold two data slots, data1 and data2, and the class, an R object that carries the table of method pointers. For a compact integer sequence, data1 is a three-element double vector (length, first value, step) and data2 starts as NULL. When code asks for an element, R calls the class’s Elt method, which computes the value from data1. No full vector is allocated.

Base R uses ALTREP for compact integer and double sequences, for numbers converted to strings only when a string is read, for memory-mapped vectors, and for wrapper objects that carry metadata such as sortedness. Packages can register classes of their own.

# Not a billion allocated integers.
x <- 1:1e9
# Computed on demand by the Elt method; x stays compact.
x[500000000]

6.5.3 Mechanism

Representation classes

ALTREP objects do not have a single uniform representation. Instead, ALTREP defines a class system. A class is registered with R and provides method pointers. Methods include Length (the number of elements), Elt (the element at index i), Dataptr (a pointer to the full data, materializing it if needed) and Get_region (copy a block of elements into a buffer).

Other methods answer questions without materializing anything. Is_sorted and No_NA report sortedness and the absence of missing values, Sum, Min and Max compute summaries, and Serialized_state gives serialize() a compact form to write. A class can leave most methods out and R uses a default.

Materialization

User code does not directly request materialization. It happens implicitly.

When user code calls length() on an ALTREP vector, R calls the Length method. It returns a number. No materialization.

When user code accesses an element by index, R calls the Elt method. It computes the value. No materialization.

When C code needs direct pointer access to the data, R calls the Dataptr method, which must return a pointer to a C array with every element in standard layout. The compact sequence class allocates an ordinary integer vector, fills it in a loop, stores it in data2, and returns its data pointer. From then on, Elt reads from data2.

x <- 1:1e8
length(x)   # no materialization: asks the Length method
x[1]        # no materialization: the element is computed
sum(x)      # no materialization either: compact sequences carry a Sum method
x[1] <- 99L # a full ordinary vector is built: the sequence is no longer a sequence

The last line is the one that costs. A compact integer sequence knows its own sum in closed form, so sum(x) returns immediately and allocates nothing. Assigning into it destroys the property that made the compact form possible. R marks every compact sequence as not mutable when it creates one, so the assignment duplicates x into an ordinary vector and changes that. Measured on this machine with 1:1e8, sum and max complete in under a fifth of a second and leave memory flat, while the single element assignment adds about 381 MiB, which is the 400 MB integer vector arriving.

What forces materialization is whether a function needs a real C array, not how much of the data it reads, and several base functions that only read do need one. In R 4.6.1, x + 1L, range(x), cumsum(x) and identical(x, 1:1e8) all expand a compact sequence in place, while sum(), max(), mean() and rev() leave it compact. Anything reaching for DATAPTR gets the array built.

Memory accounting

The compact state is small: for a sequence, a three-element double vector and the ALTREP node itself. Materializing allocates an ordinary vector on the heap, garbage-collected like any other, and the ALTREP object keeps it in data2 for as long as the object lives. An expanded compact sequence therefore costs the compact state plus the full vector.

Because compact sequences are marked not mutable, the expanded data always matches the sequence: any write duplicates first, and the duplicate is an ordinary vector with no tie to the ALTREP object.

6.5.4 Internal mechanics

Side effects on read

Materialization is a write that happens during a read, and that is the hazard for parallel R.

Suppose two threads share one compact sequence. Thread A reads elements through Elt, which checks data2, finds NULL, and computes each value from data1. Thread B evaluates x + 1L, which asks for the data pointer. Dataptr allocates a full vector on R’s heap, which can start a garbage collection, fills it, and stores it in data2 with R_set_altrep_data2. That setter goes through the write barrier, which updates reference counts and can move the node to a different list of the collector by rewriting its link pointers. Nothing on this path takes a lock.

The values thread A reads stay the same either way. What breaks is everything around them. Both threads can find data2 empty and allocate at once, on an allocator and a collector written for one thread, and A can be reading the node while B rewrites its pointer slots and header bits. An early threaded-r experiment, two threads evaluating R code against one shared heap, recorded a torn compact sequence among its failure signatures.

the object changes under the reader thread A reads through Elt reads again data2 slot written same pointer, rewritten underneath shared SEXP compact: length, first value, step materialized: a real array thread B reaches DATAPTR

At the R level both threads only read, yet thread B’s read rewrites the shared object under thread A.

ALTREP materialization is a side effect on read. It mutates SEXP state and can trigger memory allocation. Two threads cannot safely share an ALTREP vector.

Implications for fork and copy-on-write

ALTREP also changes the arithmetic of fork-based parallelism. A child forked from a parent that holds a compact sequence inherits it at almost no cost, because the compact state is about a hundred bytes. If the child then materializes it, the full vector is allocated in the child’s own memory and is private to it, so every child that does this pays for its own copy. A vector the parent had expanded before the fork would instead sit in pages the children share until something writes to them.

6.5.5 The hard part

ALTREP pays off in sequential R: large sequences cost nothing until a function needs their data, and many functions never do.

In parallel R, the deferred state is hidden state that a read can change, which is exactly what multithreaded code cannot tolerate without a lock.

One answer is not to share ALTREP objects at all. Each interpreter gets its own and materializes it privately if it must. That is safe, and it gives up sharing the data.

The other answer is to materialize before sharing. A compact sequence expanded before it is shared no longer writes to itself when read, at the price of the full allocation up front.

6.5.6 Lazy representations elsewhere

Rust’s range syntax produces a range iterator, not an allocated array. The iterator computes values on demand, and user code calls .collect() to build a Vec. Nothing is cached, so nothing is written on read.

Scala’s LazyList is immutable from the outside, but it computes each element at most once and caches it, and .force evaluates all of them. That cache is written on first access, the same shape of problem as ALTREP’s data2.

Python’s generators are lazy. Calling next() computes one element. Consuming the whole generator exhausts it. This is not true lazy sharing: a generator can only be consumed once.

6.5.7 ALTREP in threaded-r

threaded-r keeps R’s ALTREP implementation and gives each interpreter its own ALTREP class registry and its own handles for the base classes. An ALTREP object lives in one interpreter’s heap, so materializing it writes only to that interpreter’s memory.

The apartment model does not share ALTREP objects between interpreters: data crosses as serialized bytes. In R’s default serialization format (version 3), a compact sequence is written in its compact form. serialize(1:1e8, NULL) is 133 bytes, against about 400 MB with version = 2, and the receiving interpreter rebuilds a compact sequence of its own.

ALTREP materialization is implicit and happens on the first access that needs a data pointer. threaded-r uses the apartment model to prevent cross-interpreter sharing of ALTREP objects.

6.5.8 r-in-rust

rrs has no ALTREP in its object model. Its vectors are flat, and adding a callback check to every vector operation is the change that design exists to avoid. When a package creates an ALTREP object through the C API, R_new_altrep calls the class’s Length and element methods once and returns an ordinary vector holding the result (crates/rrs-abi/src/altrep.rs).

That gives up laziness, and with it any side effect a Dataptr method would perform on access. It also removes the write on read: an rrs vector is never rewritten by being looked at.

6.5.9 Open questions

Can ALTREP materialization be made thread-safe? The compact sequence class already skips the work when data2 is set, but the check and the store are separate steps, so two threads can both find it empty. A compare-and-swap on data2 would let one thread win, provided allocation itself were safe from two threads.

Does ALTREP state need a flag marking the object as “under materialization”? During materialization, this flag is set. Other threads that try to access the object wait for the flag to clear. This serializes all accesses but eliminates races.

Further reading

Where this appears

  • threaded-r ALTREP materialization is a hidden side effect on read. It mutates SEXP state, creating data-race hazards for threads.
  • r-in-rust (rrs) rrs has no ALTREP in its object model. It turns a package’s ALTREP object into an ordinary vector when the object is created.

Where to go next

Back to top