Why is the R code with `{}` faster than with `()`?

Why is R code c {}generally faster than c (), 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()
+5
source share
2 answers

baptiste has already linked the Radford Neal blog in the comments.
But since SE people do not like links to external sites, let me quote an interesting comment by the author himself (comment 33):

Yes, parentheses are still slower than braces in R 2.13.1, and in the latter R 2.14.1, although not as much as before (the patch that I proposed to reduce overall overhead in built-in functions was incorporated into later versions, which reduced this difference).

, . ( ), . , R, , , sqrt, , , , , sqrt.

, ( ) - , -
{ } - .
( ) , , .

+9
, ( ).
brace <- function(n){
w1=numeric(n)
w2=numeric(n)
r=rnorm(n)
for(i in 1:n)
w1[i]=((r[i]^2))*(1*1)
}


curly <- function(n){
w1=numeric(n)
w2=numeric(n)
r=rnorm(n)
for(i in 1:n)
w2[i]={{r[i]^2}}*{1*1}
}



microbenchmark( curly(1e5) , brace(1e5) , times = 50 ) 
Unit: milliseconds
         expr      min       lq   median       uq      max neval
 curly(1e+05) 311.4245 318.8916 324.1990 335.0928 400.8555    50
 brace(1e+05) 315.5428 323.8860 328.7982 350.7268 406.5785    50

5 1e5. :

braceV <- function(n){
w1=numeric(n)
w2=numeric(n)
r=rnorm(n)
w1=((r^2))*(1*1)
}


curlyV <- function(n){
w1=numeric(n)
w2=numeric(n)
r=rnorm(n)
w2={{r^2}}*{1*1}
}

microbenchmark( curlyV(1e5) , braceV(1e5) , times = 50 )
Unit: milliseconds
          expr      min       lq    median       uq      max neval
 curlyV(1e+05) 9.014361 9.284532  9.666867 10.81317 37.82510    50
 braceV(1e+05) 9.029408 9.373773 10.293302 10.83487 37.76596    50

0,5 .

+5

All Articles