为什么.index比.all快?

时间:2021-06-29 20:56:22

Here are two simple blocks that do the same thing:

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

a = (0..100).to_a

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

nil == a.index do |x|
  x == 1000
end

Except that the second one is consistently a little bit faster. Why?

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

                                     user     system      total        real
testing all                      1.140000   0.000000   1.140000 (  1.144535)
testing index                    0.770000   0.000000   0.770000 (  0.769195)

2 个解决方案

#1


5  

The reason is that index is a method of Array. Ruby will iterate (in C) over the items and yield them to the block in turn.

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

On the other hand, all?, none?, one? (which will all be around 30% slower), are methods of Enumerable. They will call each, which will yield to a C function which will yield to the block. The difference in timing is due to the fact that there are two yields involved.

另一方面,所有?,没有?,一个? (这些都将慢大约30%),是Enumerable的方法。他们将调用每个,这将产生一个C函数,它将产生块。时间上的差异是由于涉及两个产量的事实。

Note that specialized versions of all? et al. could be defined on Array and you would get the same performance as index, but that would be a bit ugly and redundant...

请注意所有专用版本?等。可以在Array上定义,你会得到与索引相同的性能,但这有点丑陋和冗余......

#2


1  

It could be because of the extra step ! done in each turn of the iteration with all?.

这可能是因为额外的一步!在所有迭代的每个回合中完成?

#1


5  

The reason is that index is a method of Array. Ruby will iterate (in C) over the items and yield them to the block in turn.

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

On the other hand, all?, none?, one? (which will all be around 30% slower), are methods of Enumerable. They will call each, which will yield to a C function which will yield to the block. The difference in timing is due to the fact that there are two yields involved.

另一方面,所有?,没有?,一个? (这些都将慢大约30%),是Enumerable的方法。他们将调用每个,这将产生一个C函数,它将产生块。时间上的差异是由于涉及两个产量的事实。

Note that specialized versions of all? et al. could be defined on Array and you would get the same performance as index, but that would be a bit ugly and redundant...

请注意所有专用版本?等。可以在Array上定义,你会得到与索引相同的性能,但这有点丑陋和冗余......

#2


1  

It could be because of the extra step ! done in each turn of the iteration with all?.

这可能是因为额外的一步!在所有迭代的每个回合中完成?