Re: [Rd] Speed of for loops

From: Herve Pages <hpages_at_fhcrc.org>
Date: Wed 31 Jan 2007 - 00:44:58 GMT

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.



R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Wed Jan 31 11:46:52 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 31 Jan 2007 - 02:31:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.