Speed up your R code

This short post is to share an R tip Pierre recently gave me. When you need to store values sequentially (typically inside a loop), it’s more far efficient to create the whole vector (or matrix) and to fill it, rather than to concatenate the values to your current vector (or matrix). In terms of allocation time, it’s up to 60 times faster

n=10^5
a=NULL
system.time(for (i in 1:n){a=c(a,1)})
>utilisateur     système      écoulé 
>     12.09        0.00       12.09 
 
b=rep(0,n)
system.time(for (i in 1:n){b[i]=1})
>utilisateur     système      écoulé 
>       0.21        0.00        0.20

which makes a big difference. In a Gibbs sampling loop, where a lot of other computations are done, I still have gain of 25%! For other recommendations (don’t use parentheses where you can avoid them), you can have a look on this post.

Published by Julyan Arbel

Researcher at Inria Grenoble Rhône-Alpes

4 thoughts on “Speed up your R code

Leave a comment