public
Created

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
My message:
This was tweeted recently by an R user, and after trying to figure out why this is, I am stumped:
> a <- 5; b <- 1; c <- 4
> f <- function (n) for (i in 1:n) d <- 1/{a*{b+c}}
> g <- function (n) for (i in 1:n) d <- 1/(a*(b+c))
> system.time(f(1000000))
user system elapsed
3.92 0.00 3.94
> system.time(g(1000000))
user system elapsed
4.17 0.00 4.17
(from http://radfordneal.wordpress.com/2010/08/15/two-surpising-things-about-r/)
 
Anyone know why curly braces are evaluated faster?
 
 
 
 
Duncan's response (he comments that "there is more to investigate as to the particular paths through the evaluator"):
 
I'll bite and give a slightly informal description of what
I see as going on.
 
( and { are quite different elements of the language.
For instance,
(1+2; 3)
is an error, but
 
{1+2; 3}
 
evaluates to 3 and evaluates both "terms" within the expression.
 
As a result, the evaluation path within the interpreter is quite different.
Specifically, the 1/(2+3) ends up with 3 calls to the C routine Rf_evalList()
with terms (2+3) and (2, 3).
 
1/{2+3} ends up with only two calls Rf_evalList(), evaluating with
 
(1, {4 + 5})
and
(4 , 5)
 
So there is a different and slightly shorter path, but small overhead
per call.
 
(BTW, I found this via gdb, the debugger for compiled code.)
 
D.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.