[Rd] Speed of for loops

Herve Pages hpages at fhcrc.org
Wed Jan 31 01:44:58 CET 2007


Hi,

Byron Ellis wrote:
> IIRC a for loop has more per-iteration overhead that lapply, but the
> real answer is "it depends on what you're doing exactly." I've seen it
> be a faster, slower and equal approach.

gen.iter = function(y=NA) {
 function(x) {
   y <<- if(is.na(y)) x else x+y
 }
}

sapply + gen.iter is slithly faster on small vectors:

  > x <- rep(1, 5000)
  > system.time(tt <- sapply(x,gen.iter()))
     user  system elapsed
    0.012   0.000   0.012
  > x <- rep(1, 5000)
  > system.time(tt <- for(i in 2:length(x)) {x[i] <- x[i-1]+x[i]})
     user  system elapsed
    0.016   0.000   0.016

but much slower on big vectors:

  > x <- rep(1, 10000000)
  > system.time(tt <- sapply(x,gen.iter()))
     user  system elapsed
  138.589   0.964 139.633
  > x <- rep(1, 10000000)
  > system.time(tt <- for(i in 2:length(x)) {x[i] <- x[i-1]+x[i]})
     user  system elapsed
   29.978   0.480  30.454


Cheers,
H.



More information about the R-devel mailing list