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)
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 yield
s 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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With