为什么.index比.all快?

Vla*_*ala 8 ruby performance

以下是两个执行相同操作的简单块:

a = (0..100).to_a

a.all? do |x|
  !(x == 1000)
end

nil == a.index do |x|
  x == 1000
end
Run Code Online (Sandbox Code Playgroud)

除了第二个一直快一点.为什么?

                                     user     system      total        real
testing all                      1.140000   0.000000   1.140000 (  1.144535)
testing index                    0.770000   0.000000   0.770000 (  0.769195)
Run Code Online (Sandbox Code Playgroud)

Mar*_*une 5

原因是这index是一种方法Array.Ruby将在项目上迭代(在C中)并依次将它们放到块中.

在另一方面,all?,none?,one?(将所有比较慢30%左右),是的方法Enumerable.他们将调用each,这将产生一个C函数,它将产生块.时间上的差异是由于yield涉及两个s 的事实.

请注意all?等人的专业版本.可以定义Array,你会得到相同的表现index,但这将有点丑陋和冗余......