Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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
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})
(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.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment