为什么Ruby的loop命令比true慢? [英] Why is Ruby's loop command slower than while true?
问题描述
Ruby有一个内置的loop
命令,该命令永远执行其后的块(或直到被break
停止).但是,将其与功能相似的while true
进行比较时,它的速度要慢得多:
Ruby has a built-in loop
command that executes the block following it forever (or until stopped by break
). However, when comparing it against the functionally similar while true
, it is significantly slower:
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修订版58053)[x64-mingw32])下,区别非常明显:
Under Ruby 2.4.1 (p111 (2017-03-22 revision 58053) [x64-mingw32]), the difference is striking:
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
更糟糕?
Why is there such a performance difference? And why is the single-purpose loop
command worse at its job than the general-purpose while
?
(从这里,根据CC-BY-SA许可)
(Benchmark copied from here, licensed under CC-BY-SA)
推荐答案
loop
是采用block
的内核方法.提醒一下,block
引入了新的局部变量作用域.
loop
is a kernel method which takes a block
. As a reminder, a block
introduces new local variable scope.
例如:
loop do
a = 2
break
end
puts a
将返回错误,例如:" NameError:main:Object 的未定义局部变量或方法'a'" 另一方面:
Will return an error such as: "NameError: undefined local variable or method `a' for main:Object" On the other hand:
while true
a = 2
break
end
p a #=> return a = 2
因此,loop
创建某种局部变量(例如用于break语句的局部变量)将在其范围之内,我不会感到惊讶.在每次迭代中创建/删除这些变量都会减慢该过程.
So I wouldn't be surprised that loop
creates some sort of local variable(s) such as one for the break statement that is (are) going to be in its scope. Creating/deleting those variables at every iteration slow down the process.
这篇关于为什么Ruby的loop命令比true慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!