library(tidyverse)
library(lobstr)11 What data costs in memory
11.1 Introduction
R works on data in memory. Everything you read_csv() or read_parquet() into a variable sits in your computer’s RAM, and when the RAM runs out, R stops. Before moving data out to files and datasets, it is worth knowing what it costs where it lives now, and how R avoids paying that cost twice.
The definitive account is in the first chapters of Advanced R, “Names and values” and “Vectors” (Wickham 2019, chaps. 2–3), which this chapter applies to physics tables. It uses the lobstr package (Wickham 2026), which Advanced R uses for the same job: obj_size() measures how much memory an object occupies, accounting for parts it shares with other objects, and obj_addr() reports where in memory an object lives.
Prerequisites
11.2 The size of a table
Read the dimuon data and measure it:
dimuon <- read_csv("data/dimuon.csv.gz")
obj_size(dimuon)
#> 9.57 MBThat is almost exactly what you would predict by hand. readr reads every number as a double, R’s 8-byte floating-point type, so 119,528 rows times 10 columns times 8 bytes is 9.56 MB, plus a little for the column names and other attributes:
nrow(dimuon) * ncol(dimuon) * 8
#> [1] 9562240For tables of numbers, that is the rule of thumb to carry around: rows × columns × 8 bytes. A billion events with ten numbers each would need 80 GB, which is more memory than most computers have.
Some of those columns do not need 8 bytes. run, event and the two charges are whole numbers, and R’s integers take 4 bytes. readr’s col_types argument says what each column is; col_integer() and col_double() are the two you will use most:
dimuon_typed <- read_csv(
"data/dimuon.csv.gz",
col_types = cols(
run = col_integer(),
event = col_integer(),
mu1_charge = col_integer(),
mu2_charge = col_integer(),
.default = col_double()
)
)
obj_size(dimuon_typed)
#> 7.65 MBFour columns at half the size saves a fifth of the total. Declaring types is good practice for another reason too: it documents what the data is, and readr will complain if a value does not fit.
Notice what is missing from R’s menu: there is no 4-byte floating-point type. Every non-integer number in R is a double, with 53 bits of precision, about 16 significant digits. A measurement with four significant digits uses a quarter of those bits for information and the rest for noise or for nothing, which is the same waste Chapter 4 found on disk. One remedy is the one used there: store numbers as integers in a small unit, such as momenta in MeV rather than GeV. Another, coming in Chapter 14, is to leave the data in Arrow’s memory, which does have 4-byte floats.
11.3 Strings and factors
Character columns work differently. R keeps a single global pool of strings, and a character vector holds pointers into it, 8 bytes each on a 64-bit computer, however long the strings are (Wickham 2019, sec. 2.4). So a million copies of the same word cost a million pointers and one copy of the word:
region <- rep(c("barrel", "endcap"), times = 500000)
obj_size(region)
#> 8.00 MBA factor stores the same information as an integer code for each element, 4 bytes each, plus one copy of each distinct value, the factor’s levels (Wickham 2019, sec. 3.4):
region_factor <- factor(region)
levels(region_factor)
#> [1] "barrel" "endcap"
obj_size(region_factor)
#> 4.00 MBHalf the size. This is dictionary encoding: replace each value with a short code and keep a dictionary of what the codes mean. Parquet uses exactly the same trick on disk (Chapter 13), and it is one reason a column of repeated labels, like a detector name or a trigger type, costs almost nothing in a Parquet file.
11.4 Some vectors take no space at all
Since R 3.5.0, some vectors are stored in a compact form until you need their elements, a feature called ALTREP, for alternative representations. The most common case is a sequence. A billion integers would take 4 GB, but 1:1e9 costs a few hundred bytes, because R stores only its start and end:
obj_size(1:1e9)
#> 680 BBase R’s older object.size() does not know about ALTREP, or about shared components, so it can mislead badly; this is one reason Advanced R recommends lobstr (Wickham 2019, sec. 2.4):
object.size(1:1e9)
#> 4000000048 bytes11.5 Copy-on-modify
R has a property that protects you from a whole class of bugs: when you modify an object that another name also points to, R copies it first, so the other name never sees the change. Advanced R calls this copy-on-modify (Wickham 2019, sec. 2.3). It sounds expensive, and for a big table it would be, but R is careful about what it copies.
A data frame is a list of columns, and each column is a separate vector. When mutate() changes one column, the new data frame shares every other column with the old one. Here the transverse momenta of the leading muon are converted to MeV:
dimuon_mev <- dimuon |>
mutate(mu1_pt = mu1_pt * 1000)
obj_addr(dimuon$mu2_pt) == obj_addr(dimuon_mev$mu2_pt)
#> [1] TRUE
obj_addr(dimuon$mu1_pt) == obj_addr(dimuon_mev$mu1_pt)
#> [1] FALSEThe mu2_pt column is the same vector in both tables, at the same address; only mu1_pt is new. obj_size() given two objects reports their combined size, counting shared parts once:
obj_size(dimuon, dimuon_mev)
#> 10.52 MBThe two tables together cost the original plus one column. Selecting columns is cheaper still, since the result shares every column it keeps; filtering rows, by contrast, has to build new vectors for every column, because each one loses elements. Advanced R has the full story, including the cases where R can skip the copy altogether and modify an object in place (Wickham 2019, sec. 2.5).
11.6 How much is in use?
mem_used() reports how much memory R is using in total, for everything in the session:
mem_used()
#> 124.68 MBWhen an analysis is about to run out of memory, three questions help. Do I need every column? Read only what you use, with col_select in read_csv() and read_parquet(). Am I storing numbers in the right type? Integers and factors are half the size of doubles and strings. And do I need the data in R at all? Very often the answer is no. A histogram of a billion events takes a few kilobytes, and arrow and duckdb can compute it from files on disk without ever loading the events (Chapter 14, Chapter 15). Bring the summary into R, not the data.
11.7 Summary
A table of numbers costs about rows × columns × 8 bytes in R, because every non-integer number is an 8-byte double; declaring integer columns, and using factors instead of repeated strings, can halve that. Character vectors point into a global string pool, factors use dictionary encoding, and ALTREP lets some vectors, like sequences, take almost no space. Copy-on-modify means a changed object never surprises another name that points to it, and because data frames are lists of columns, R copies only the columns that change. lobstr’s obj_size() and obj_addr() make all of this visible.
11.8 Exercises
- Read the star catalog twice, once with default column types and once with
source_idas an integer. How much memory does the change save? Why issource_ida good candidate andg_magnot? - Compare the sizes of a vector of ten million doubles, ten million integers and ten million logical values. How many bytes does R use for each logical value? (Advanced R, chapter 3, explains why.)
- Use
obj_addr()to check whetherselect()andfilter()copy the columns they return. Then checkarrange(). - Convert the dimuon kinematics to integers: transverse momenta in MeV, and pseudorapidity and azimuth in units of 10−4. How much memory does the table take now? What precision have you kept, and is it enough?
- A magnetometer that records three components once a second runs for a year. How much memory would a year of readings take as doubles? As integers in units of 0.01 nT? Using the compression you measured in Chapter 4, roughly how large would the file be?