Readability vs speed in R

February
19th,
2011

I have bad news for those of you trying to produce lucid code!

In his blogRadford M. Neal, Professor at the University of Toronto, published an article with the headline Two Surprising Things about R.
He worked out, that parentheses in mathematical expression slow down the run-time dramatically! In contrast it seems to be less time consuming to use curly brackets. I verified these circumstances to be true:

>x=10>f<-function(n)for(iin1:n)1/(1*(1+x))>g<-function(n)for(iin1:n)(((1/(((1*(((1+x)))))))))>system.time(f(10^6))usersystemelapsed2.2310.0002.232>system.time(g(10^6))usersystemelapsed3.8960.0003.923>># in contrast with curly brackets>h<-function(n)for(iin1:n)1/{1*{1+x}}>i<-function(n)for(iin1:n){{{1/{{{1*{{{1+x}}}}}}}}}>system.time(h(10^6))usersystemelapsed1.9740.0001.974>system.time(i(10^6))usersystemelapsed3.2040.0003.228

As you can see adding extra parentheses is not really intelligent concerning run-time, and not in a negligible way. This fact shocked me, because I always tried to group expressions to increase the readability of my code! Using curly brackets speeds up the execution in comparison to parentheses. Both observations are also surprising to me!
So the conclusion is: Try to avoid redundant parentheses and/or brackets!

To learn more about the why you are referred to his article. He also found a interesting observation about squares.
In a further article he presents some patches to speed up R.