[R] Alternate to for-loop
Wacek Kusnierczyk
Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Feb 17 12:11:35 CET 2009
Stefan Evert wrote:
>
>> hmm, would you be saying that r's vectorised performance is overhyped?
>> or is it just that non-vectorised code in r is slow?
>
> What I meant, I guess, was (apart from a little bit of trolling) that
> I'd had misconceptions about the speed differences between loops and
> vectorised code. In particular, I had entertained the naive belief
> that vectorised solutions are always highly efficient (I wonder if I'm
> the only one who was naive enough to think this ..), so I was very
> much surprised to find a loop in an interpreted language like Lua to
> be faster than vectorised R code.
>
> My silly little benchmark translated the Lua code
>
> sum = 0
> for i=1,N do sum = sum + i end
>
> into vectorised R
>
> sum(as.numeric(1:N))
>
what you're benchmarking here is a lump of vector allocation and the
actual summing. assuming that you already have generated and stored the
values to be summed, the runtime differs a bit:
system.time(sum(as.numeric(1:10^8)))
system.time({ x = 1:10^8 })
system.time({ y = as.numeric(x) })
system.time(sum(y))
though again, it's a factor below one order of magnitude.
vQ
More information about the R-help
mailing list