gpt4 book ai didi

r - 为什么带有 `{}` 的 R 代码比带有 `()` 的 R 代码快?

转载 作者:行者123 更新时间:2023-12-04 12:19:48 24 4
gpt4 key购买 nike

为什么R代码带有{}总体来说比 () 快,下面的例子?

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()

最佳答案

巴蒂斯特 已经在评论中链接了 Radford Neal 的博客。
但由于 SE 人不喜欢链接到外部网站,让我引用作者本人的一个有趣评论(评论 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.


知道了, ( )似乎是一个运算符——就像一个基本上什么都不做的函数——
{ }是一种语言结构。
括号 ( )合并一些所有操作符通用的开销代码,这些代码实际上不需要它们。

关于r - 为什么带有 `{}` 的 R 代码比带有 `()` 的 R 代码快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15926553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com