Skip to content

Instantly share code, notes, and snippets.

@jaye-ross
Created April 19, 2015 19:52
Show Gist options
  • Save jaye-ross/83765d754bd59d1135f8 to your computer and use it in GitHub Desktop.
Save jaye-ross/83765d754bd59d1135f8 to your computer and use it in GitHub Desktop.
Benchmarking in R: pre-allocated vectors vs vector concatenation
f1 = function(n){
x = double(n)
for(i in 1:n) x[i] = runif(1)
return(x)
}
f2 = function(n){
x = c()
for(i in 1:n) x = c(x,runif(1))
return(x)
}
n = 1000
microbenchmark(
f1(n),
f2(n)
)
## As you see, they are virtually the same, which was surpring to me.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment