gpt4 book ai didi

ruby - 为什么 Ruby 的循环命令比 while true 慢?

转载 作者:数据小太阳 更新时间:2023-10-29 07:35:27 26 4
gpt4 key购买 nike

Ruby 有一个内置的 loop 命令,可以永远执行它后面的 block (或者直到被 break 停止)。但是,当将它与功能相似的 while true 进行比较时,它的速度要慢得多:

require "benchmark/ips"

NUMBER = 100_000_000

def fast
index = 0
while true
break if index > NUMBER
index += 1
end
end

def slow
index = 0
loop do
break if index > NUMBER
index += 1
end
end

Benchmark.ips do |x|
x.report("While Loop") { fast }
x.report("Kernel loop") { slow }
x.compare!
end

在 Ruby 2.4.1 (p111 (2017-03-22 revision 58053) [x64-mingw32]) 下,差异是惊人的:

Warming up --------------------------------------
While Loop 1.000 i/100ms
Kernel loop 1.000 i/100ms
Calculating -------------------------------------
While Loop 0.630 (± 0.0%) i/s - 4.000 in 6.350897s
Kernel loop 0.190 (± 0.0%) i/s - 1.000 in 5.274249s

Comparison:
While Loop: 0.6 i/s
Kernel loop: 0.2 i/s - 3.32x slower

为什么会有这样的性能差异?为什么单一用途的 loop 命令比通用的 while 命令更差

(基准复制自 here,根据 CC-BY-SA 许可)

最佳答案

loop 是一个采用block 的内核方法。提醒一下, block 引入了新的局部变量作用域

例如:

loop do
a = 2
break
end
puts a

将返回一个错误,例如:“NameError: undefined local variable or method `a' for main:Object”另一方面:

while true
a = 2
break
end
p a #=> return a = 2

所以我不会对 loop 创建某种局部变量感到惊讶,例如将在其范围内的 break 语句。在每次迭代中创建/删除这些变量会减慢该过程。

关于ruby - 为什么 Ruby 的循环命令比 while true 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45069756/

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