Created
January 16, 2014 01:16
-
-
Save JonRowe/8448064 to your computer and use it in GitHub Desktop.
TIL that `empty?` is still significantly faster than `any?` despite `any?` being lazy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
array = 10000000.times.to_a | |
puts "Any" | |
puts Benchmark.measure { 1000.times { array.any? } } | |
puts "Empty" | |
puts Benchmark.measure { 1000.times { array.empty? } } | |
puts "Iterating over the entire collection" | |
puts Benchmark.measure { 1000.times { array.each {} } } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Any | |
0.000000 0.000000 0.000000 ( 0.000303) | |
Empty | |
0.000000 0.000000 0.000000 ( 0.000076) | |
Iterating over the entire collection | |
467.250000 0.150000 467.400000 (468.296172) |
The complex example you provide is the worst case scenario, it never returns true so iterates over the entire collection.
Is it the extra logic cruft around detecting no block was passed, and deciding what to do about it... ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I thought this might be because the you're comparing C code to ruby interpreted code. But you you can also supply a block to any?
Note I reduced the number of iterations on each because it's so damn slow.
Output:
I was a little surprised by this, but perhaps it optimises for the default implementation??
Note I have to drop the any? complex block benchmark down to 10 iterations because it's so slow.
Output: