Skip to content

Instantly share code, notes, and snippets.

@vsbuffalo
Created August 18, 2010 20:19
Show Gist options
  • Save vsbuffalo/536042 to your computer and use it in GitHub Desktop.
Save vsbuffalo/536042 to your computer and use it in GitHub Desktop.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment