Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .index faster than .all?

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)
like image 680
Vlad the Impala Avatar asked Mar 03 '13 21:03

Vlad the Impala


1 Answers

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.

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.

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...

like image 108
Marc-André Lafortune Avatar answered Sep 29 '22 13:09

Marc-André Lafortune