Skip to content

Instantly share code, notes, and snippets.

@rolentle
Created May 3, 2018 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolentle/98e9385d0d777ea05ae30e4e8136ef91 to your computer and use it in GitHub Desktop.
Save rolentle/98e9385d0d777ea05ae30e4e8136ef91 to your computer and use it in GitHub Desktop.
any vs length > 0
require 'benchmark'
a = []
iterations = 1_000_000
puts "for empty array"
Benchmark.bm do |x|
x.report("length") { iterations.times do; a.length > 0; end }
x.report("any") { iterations.times do; a.any?; end }
end
# user system total real
#length 0.030000 0.000000 0.030000 ( 0.038053)
#any 0.040000 0.000000 0.040000 ( 0.056048)
puts "for full array"
b = (1..100).to_a
Benchmark.bm do |x|
x.report("length") { iterations.times do; b.length > 0; end }
x.report("any") { iterations.times do; b.any?; end }
end
# user system total real
#length 0.040000 0.000000 0.040000 ( 0.039192)
#any 0.050000 0.000000 0.050000 ( 0.056181)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment