Skip to content

Instantly share code, notes, and snippets.

@miguelsan
Forked from rafmagana/include_vs_when.rb
Created January 17, 2011 23: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 miguelsan/783662 to your computer and use it in GitHub Desktop.
Save miguelsan/783662 to your computer and use it in GitHub Desktop.
Improved benchmark to see which is faster, either when *array or array.include?
require 'benchmark'
class Dummy
class << self
def when_find(*args)
case args.first
when :first, :last, :all
send(args.first)
else
find_with_ids(*args)
end
end
def include_find(*args)
if [:first, :last, :all].include?(args.first)
send(args.first)
else
find_with_ids(*args)
end
end
def first;end
def last;end
def all;end
def find_with_ids(*args);end
end
end
Benchmark.bmbm do |bm|
N = 999999
bm.report("first with when:") { N.times {Dummy.when_find :first } }
bm.report("first with include?:") { N.times {Dummy.include_find :first } }
bm.report("last with when:") { N.times {Dummy.when_find :last } }
bm.report("last with include?:") { N.times {Dummy.include_find :last } }
bm.report("all with when:") { N.times {Dummy.when_find :all } }
bm.report("all with include?:") { N.times {Dummy.include_find :all } }
bm.report("ids with when:") { N.times {Dummy.when_find [1,2,3] } }
bm.report("ids with include?:") { N.times {Dummy.include_find [1,2,3] } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment