# Readability vs speed in R

**binfalse » R**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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

In his blog Radford 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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | > x=10 > f <- function (n) for (i in 1:n) 1/(1*(1+x)) > g <- function (n) for (i in 1:n) (((1/(((1*(((1+x))))))))) > system.time(f(10^6)) user system elapsed 2.231 0.000 2.232 > system.time(g(10^6)) user system elapsed 3.896 0.000 3.923 > > # in contrast with curly brackets > h <- function (n) for (i in 1:n) 1/{1*{1+x}} > i <- function (n) for (i in 1:n) {{{1/{{{1*{{{1+x}}}}}}}}} > system.time(h(10^6)) user system elapsed 1.974 0.000 1.974 > system.time(i(10^6)) user system elapsed 3.204 0.000 3.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.

**leave a comment**for the author, please follow the link and comment on their blog:

**binfalse » R**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.