From hpages at fhcrc.org  Wed Jan 31 01:44:58 2007
From: hpages at fhcrc.org (Herve Pages)
Date: Tue, 30 Jan 2007 16:44:58 -0800
Subject: [Rd] Speed of for loops
In-Reply-To: <7098abec0701301601h6286328aic50043f94601c04a@mail.gmail.com>
References: <op.tmyqilgbffxks9@norisk>
	<45BFC6B8.8040101@fhcrc.org>	<7098abec0701301523u8c06819nd896cb78f5ede73a@mail.gmail.com>	<45BFD7E3.7040708@ebi.ac.uk>
	<7098abec0701301601h6286328aic50043f94601c04a@mail.gmail.com>
Message-ID: <45BFE68A.1090701@fhcrc.org>

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.



[Rd] Speed of for loops
Herve Pages