guy guy - 9 months ago 45
R Question

Does appending to a list in R result in copying?

Suppose I have create a list in R and append to it as follows:

x = list(10)
x[[2]] = 20

Is this equivalent to

x = list(10)
x = list(10, 20)

? I'm not so experienced with the particular details of how R handles lists in memory, but my limited understanding is that it tends to be copy-happy; what would be ideal for me would be that the first option doesn't involve essentially creating another list in memory, but just results in setting aside a new place in memory for the appended value. Essentially, if I have a big list, I don't want R to make another copy of it if I just want to append something to it.

If the behaviour I want is not what is given here, is there any other way I can get the desired effect?

Answer Source

I'm fairly confident the answer is "no". I used the following code to double check:

Rprof(tmp <- tempfile(), memory.profiling = TRUE)

x <- list()
for (i in 1:100) x[[i]] <- runif(10000)

summaryRprof(tmp, memory = "stats")

The output:

# index: runif
#      vsize.small  max.vsize.small      vsize.large  max.vsize.large 
#            76411           381781           424523          1504387 
#            nodes        max.nodes     duplications tot.duplications 
#          2725878         13583136                0                0 
#          samples 
#                5 

The relevant part being duplications = 0.