Why is the R code with {}
in general faster than the one with ()
, example below ?
n=10000000
w1=numeric(n)
w2=numeric(n)
r=rnorm(n)
t1=Sys.time()
for(i in 1:n)
w1[i]=((r[i]^2))*(1*1)
t1-Sys.time()
t1=Sys.time()
for(i in 1:n)
w2[i]={{r[i]^2}}*{1*1}
t1-Sys.time()
There is a lot of overhead in the processing because R needs to check the type of a variable nearly every time it looks at it. This makes it easy to change types and reuse variable names, but slows down computation for very repetitive tasks, like performing an action in a loop.
(You'll learn how to access this C++ code from R in Rcpp.) The C++ implementation is around 1x faster than the best pure R implementation.
The total duration of the R Script is approximately 11 minutes and 12 seconds, being roughly 7.12 seconds per loop. The total duration of the Python Script is approximately 2 minutes and 2 seconds, being roughly 1.22 seconds per loop. The Python code is 5.8 times faster than the R alternative!
baptiste already linked Radford Neal's blog in the comments.
But since the SE people don't like links to external sites, let me quote an interesting comment of the author himself (comment 33):
Yes, parentheses are still slower than curly brackets in R 2.13.1, and in the latest R 2.14.1, though not by as much as before (a patch I suggested to reduce general overhead in built-in functions was incorported in later releases, which reduced this difference).
There’s no good reason for parentheses to be slower. I suggested another change (to just a couple lines of code) that would speed up parentheses. Luke Tierney responded that this patch should on no account be incorporated into R, on the basis that parentheses are an operator just like sqrt, and that there should therefore be nothing in the code implementing parentheses that departs from how operators like sqrt are implemented.
Knowing that, ( )
appears to be an operator - much like a function doing basically nothing -
while { }
is a language construct.
The parentheses ( )
incorporate some overhead code common to all operators which is actually of no need for them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With