Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created August 6, 2009 12:20
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 jodosha/163274 to your computer and use it in GitHub Desktop.
Save jodosha/163274 to your computer and use it in GitHub Desktop.
require "benchmark"
require "rubygems"
require "activesupport"
module Enumerable
def else(&block)
self.respond_to?('empty?') && self.empty? ? yield : self
end
def else_try(&block)
self.try(:empty?) ? yield : self
end
def else_try_with_no_block
self.try(:empty?) ? yield : self
end
def else_any
not any? ? yield : self
end
end
TIMES = 5_000_000
EMPTY_ARRAY = []
FILLED_ARRAY = [1]
Benchmark.bm(40) do |b|
b.report("empty array with else") do
TIMES.times do |i|
EMPTY_ARRAY.each do |element|
end.else do
end
end
end
b.report("empty array with else_try") do
TIMES.times do |i|
EMPTY_ARRAY.each do |element|
end.else_try do
end
end
end
b.report("empty array with else_try_with_no_block") do
TIMES.times do |i|
EMPTY_ARRAY.each do |element|
end.else_try_with_no_block do
end
end
end
b.report("empty array with else_any") do
TIMES.times do |i|
EMPTY_ARRAY.each do |element|
end.else_any do
end
end
end
b.report("filled array with else") do
TIMES.times do |i|
FILLED_ARRAY.each do |element|
end.else do
end
end
end
b.report("filled array with else_try") do
TIMES.times do |i|
FILLED_ARRAY.each do |element|
end.else_try do
end
end
end
b.report("filled array with else_try_with_no_block") do
TIMES.times do |i|
FILLED_ARRAY.each do |element|
end.else_try_with_no_block do
end
end
end
b.report("filled array with else_any") do
TIMES.times do |i|
FILLED_ARRAY.each do |element|
end.else_any do
end
end
end
end
__END__
                                              user     system      total        real
empty array with else                    17.920000   0.070000  17.990000 ( 18.145576)
empty array with else_try                16.880000   0.050000  16.930000 ( 17.086479)
empty array with else_try_with_no_block   4.650000   0.020000   4.670000 (  4.694035)
empty array with else_any                 4.010000   0.010000   4.020000 (  4.045465)
filled array with else                   16.470000   0.050000  16.520000 ( 16.674411)
filled array with else_try               15.370000   0.060000  15.430000 ( 15.563179)
filled array with else_try_with_no_block  4.600000   0.010000   4.610000 (  4.639092)
filled array with else_any                7.710000   0.020000   7.730000 (  7.783507)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment