r - Why do parentheses slow down my program in R
问题描述
I caught some redundant parentheses in my friend's code and it really slowed down the execution time. If there any explanation for this. Please check out this example code
Python is also a (quesi) interpreted language and doesn't suffer from this program.
# 0.370 seconds
x <- 0
while (x < 100000) {
10
x = x + 1
}
# 0.743 seconds
x <- 0
while (x < 100000) {
((((((((((10))))))))))
x = x + 1
}
解决方案
虽然akrun 的评论谈到R v2.11.1
,但事情并没有真正改变。
?paren (括号和大括号)的帮助说,与其他一些语言不同,括号和大括号是 R 中的原始函数。这意味着当你写1 时a <- 1
,1 只是一个 1。但是,如果你写a <- (1)
,1 是在一个函数里面。
因此,即使您要运行简单的评估,括号也会花费更多时间(当您评估一个函数和一个数字时)。
library(microbenchmark)
microbenchmark("simple" = {a <- 1},
"parentheses" = {
a <- (1)})
Unit: nanoseconds
expr min lq mean median uq max neval cld
simple 0 100 89 100 100 700 100 a
parentheses 100 100 310 200 200 16000 100 a
sessionInfo()
R version 3.5.3 (2019-03-11)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)