In R, is growing a list just as inefficient as growing a vector?

some_list <- list()

for (i in 1:1000) {
    some_list[[i]] <- i
}

I am wondering if this is just as inefficient had some_list been a vector instead.

Upvotes: 8

Views: 342

Answers (1)

JRR
JRR

Reputation: 3243

The answer seems to be 'yes'. You can benchmark it.

f = function() {
  some_list <- list()
  for (i in 1:100000)
    some_list[[i]] <- i
}

g = function() {
  some_vector <- c()
  for (i in 1:100000)
    some_vector[i] <- i
}

h = function() {
  some_list <- vector("list", 100000)
  for (i in 1:100000)
    some_list[[i]] <- i
}

k = function() {
  some_vector <- integer(100000)
  for (i in 1:100000)
    some_vector[i] <- i
}

microbenchmark::microbenchmark(f(), g(), h(), k(), times = 10)
Unit: milliseconds
 expr       min        lq      mean    median        uq      max neval
  f() 27.723670 28.058052 31.043727 28.812197 33.973669 38.58484    10
  g() 20.699626 21.235849 23.029765 21.531695 26.419720 28.04681    10
  h()  7.056399  7.151585  7.887856  7.356198  7.936945 10.80190    10
  k()  6.025570  6.076456  7.194970  6.408183  7.808957 11.00644    10

Upvotes: 8

Related Questions