Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created April 9, 2011 17:27
Show Gist options
  • Save jodosha/911578 to your computer and use it in GitHub Desktop.
Save jodosha/911578 to your computer and use it in GitHub Desktop.
Benchmark for Array#empty? vs Array#any?
#!/usr/bin/env ruby -w
require 'benchmark'
TIMES = 10_000_000
EMPTY_ARRAY = [ ]
FILLED_ARRAY = [ 1 ]
Benchmark.bm(30) do |b|
b.report "! Array#empty? with empty array" do
TIMES.times do |i|
!EMPTY_ARRAY.empty?
end
end
b.report "! Array#empty? with filled array" do
TIMES.times do |i|
!FILLED_ARRAY.empty?
end
end
b.report "Array#any? with empty array" do
TIMES.times do |i|
EMPTY_ARRAY.any?
end
end
b.report "Array#any? with filled array" do
TIMES.times do |i|
FILLED_ARRAY.any?
end
end
end
__END__
user system total real
! Array#empty? with empty array 2.480000 0.000000 2.480000 ( 2.476914)
! Array#empty? with filled array 2.490000 0.000000 2.490000 ( 2.490273)
Array#any? with empty array 4.210000 0.000000 4.210000 ( 4.229243)
Array#any? with filled array 8.640000 0.010000 8.650000 ( 8.661541)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment