6.4 Copy-on-Modify, NAMED, and Reference Tracking

R RUNTIMESTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page What Is an R Object?, SEXPs

6.4.1 Motivation

A common belief about R is that it copies everything. It does copy data, but only when a value it is about to change may also be reachable some other way. The bookkeeping that decides this is one of the first things to break when two threads share R objects.

6.4.2 The problem

A statement like y <- x creates a new binding, and the question is whether it also copies the data inside x. If R copied on every assignment, simple scripts would allocate enormous amounts of memory. If R never copied, modifying x after y <- x would also change y, which breaks R’s value semantics.

R takes a third path: share on assignment, copy on modification. What makes this safe is reference counting. R counts the references to each object from bindings, list elements and attributes. With one reference, a write can happen in place. With more than one, R copies first.

6.4.3 Mental model

In R, most assignments do not copy. The variable x and the variable y point to the same data.

x <- c(1, 2, 3)
y <- x

Both names bind to the same vector. No copy happens: the vector exists once in memory, and x and y both refer to it.

Now modify y.

x <- c(1, 2, 3)
y <- x
y[1] <- 10

At the assignment to y[1], R copies. It allocates a new vector, copies the values across, and changes element 1 of the copy. x still refers to the original vector [1, 2, 3], and y now refers to the new one, [10, 2, 3].

This behavior is copy-on-modify. Assignment looks like a copy, but the copy waits until a write arrives, so unchanged data is shared and no write is ever visible through another name.

6.4.4 Mechanism

The NAMED field

Every SEXPREC header has a 16-bit field called named. Before R 4.0.0 it held NAMED, a coarse marker: 0 for an object bound to no symbol, 1 for one symbol, 2 or more for “possibly shared”. Assignment raised it, and nothing lowered it when a binding went away. Since R 4.0.0 the same bits hold a reference count, REFCNT. The name survives in the macros: in R 4.6.1, NAMED(x) is defined as REFCNT(x).

If the count is 1, only one reference reaches the object, and a write can modify it in place without being visible through any other name. If it is greater than 1, which is what the MAYBE_SHARED macro tests, R duplicates the object and writes into the copy.

GNU R 4.6.1, and threaded-r as a fork of it, decide whether to copy from the reference count in the named field. A count of 1 allows an in-place write. A count above 1 makes R duplicate first.

The assignment flow

When R evaluates x <- value, several steps occur.

First, R evaluates the right-hand side to produce a SEXP. Second, R looks up or creates the variable name x in the current environment. Third, R stores a pointer to the SEXP in that variable binding.

The count changes in the third step. A binding is a cell in the environment’s frame, and the function that writes the cell (SETCAR, in memory.c) increments the count of the new value and decrements the count of the value the binding held before. Stores into list elements and attributes go through setters that do the same, and rm() decrements the count of the value it unbinds.

Subassignment triggers copy

Subassignment is where the count is consulted. R evaluates x[1] <- 10 as x <- `[<-`(x, 1, value = 10). If the vector bound to x has a count of 1, [<- changes it in place and the assignment rebinds x to the same object.

If the count is 2 or more, [<- duplicates the vector, changes the copy, and the copy is bound to x. The original vector is unchanged for whoever else holds it.

x <- c(1, 2, 3)
y <- x
# x and y refer to the same vector. Its reference count is 2.
y[1] <- 10
# R copies the vector and modifies the copy, which is bound to y.
# x still refers to [1, 2, 3], y to [10, 2, 3]. Each vector now has a count of 1.

6.4.5 Internal mechanics

Reference counting without atomic operations

The count is not atomic. It is a 16-bit bit field inside the 64-bit sxpinfo word at the start of the SEXPREC header, so an increment is a plain, non-atomic read-modify-write of those 16 bits. If two threads update it at the same time, both can read the same old value and write back their own result, and one update is lost. The same word holds the type, the mark bit the garbage collector sets, and other flags, and the C memory model treats adjacent bit fields as one memory location, so racing updates to neighboring fields are a data race even where the compiled code writes only the 16 count bits.

The reference count is a non-atomic bit field in the SEXPREC header. Two threads cannot safely increment or decrement it concurrently.

This is one reason naive shared-memory threading of R does not work. Two threads that share a SEXP both update its count as they bind and unbind it, and a lost update leaves the count wrong. A count that is too low lets R modify in place an object another name still sees. A count that is too high only costs an unneeded copy.

R could be modified to use atomic reference counting. The count would move out of the shared bit field into a word of its own, and every increment and decrement would be an atomic operation. That would make the count safe to update from two threads, though not the rest of the header.

When NAMED is not enough

Since R 4.0.0 the count includes references from other objects, not only from names. If a vector is an element of a list, the list’s reference counts, and it keeps counting after the list is gone.

x <- c(1, 2, 3)
l <- list(x)  # the vector's count is now 2
rm(l)         # the list is unbound, but its reference still counts
gc()
tracemem(x)
x[1] <- 10    # tracemem reports a copy

Removing the binding to the list does not touch the list’s own reference to the vector. Nothing decrements it, a collection included, so the next write to x duplicates the vector.

6.4.6 Concurrency and the apartment model

The apartment-model in threaded-r solves the reference counting problem by isolation. Each interpreter owns its heap and its SEXPs. No SEXP is shared between interpreters except immortal constants. Each SEXP’s count is updated by one thread only, so there is no race and no need for atomic operations. The cost is that objects cannot be passed between interpreters by reference.

If an interpreter wants to send data to another interpreter, the data must be serialized and copied. The receiving interpreter creates new SEXPs in its own heap. This eliminates reference counting races. It also eliminates the possibility of shared in-place modification.

threaded-r uses the apartment model. Each interpreter owns its mutable SEXPs. Reference counts are updated per-interpreter, with no cross-interpreter races.

6.4.7 r-in-rust

rrs has to give R code the same copy-on-modify semantics, and it does so with the same kind of counter. Every object in its heap carries a refs field, a saturating 8-bit count that the evaluator raises and lowers at binding and argument boundaries. A count above 1 means copy before mutating, and a count pinned at the maximum stands in for R’s MARK_NOT_MUTABLE (crates/rrs-runtime/src/lib.rs).

The counter is a plain integer, not an atomic one. That is safe because an rrs interpreter is one value owned by one thread, heap included, so no other thread can reach an object while its count changes. Inside the interpreter, the decision to copy is still made at run time, as in GNU R.

6.4.8 The hard part

Copy-on-modify works well for single-threaded R: updating the count and checking it before a write are both cheap.

With threads it becomes a cost question. With atomic reference counting, every binding, list store and attribute store pays for an atomic read-modify-write, which is slower than a plain load and store even without contention. When several threads update the same count, they also contend for the cache line that holds it, so the cost grows with the sharing.

An alternative is to use thread-local reference counts. Each thread has its own reference counts for the objects it owns. Threads do not race because they touch disjoint sets of objects. But this requires a design where objects do not move between threads, or where the count is recomputed when objects move.

6.4.9 Open questions

Can R use atomic reference counts without severe performance cost? Measurements on contended atomic operations are needed.

If a SEXP moves from one interpreter to another, how must its reference count be recomputed? Must it be reset to 1? Must the receiving interpreter scan to find all references?

Further reading

R Internals, Section 1.1.2, “Rest of header”, on the named field: https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Rest-of-header

GNU R source: FIX_REFCNT and the setters in src/main/memory.c, which keep the count, and the MAYBE_SHARED macro in src/include/Rinternals.h, which decides when duplicate() (src/main/duplicate.c) runs.

Hadley Wickham, Advanced R, Chapter 2, “Names and Values”: https://adv-r.hadley.nz/names-values.html

Where this appears

  • threaded-r Naive sharing of SEXPs across threads breaks here. Each thread owns its objects.
  • r-in-rust (rrs) rrs keeps R’s reference count as a plain per-object counter. Each interpreter’s heap belongs to one thread, so the counter needs no atomics.

Where to go next

Back to top