Skip to content

Instantly share code, notes, and snippets.

@yoppi
Created February 7, 2017 02:08
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 yoppi/fd7dff91a1186dd9125594f3a78ae22f to your computer and use it in GitHub Desktop.
Save yoppi/fd7dff91a1186dd9125594f3a78ae22f to your computer and use it in GitHub Desktop.
each君 vs enumerable君
require 'benchmark'
N = 5
TRY = 1_000_000
campaign = Struct.new("Campagin", :id)
campaings = []
N.times { |i| campaings << campaign.new(i+1) }
def each(ary)
id = nil
ary.each do |c|
next if c.nil?
next id = c.id if id.nil?
if id != c.id
return false
end
end
true
end
def compact_map_uniq(ary)
ary.compact.map(&:id).uniq.size <= 1
end
Benchmark::bmbm do |b|
b.report("each") do
TRY.times do
each(campaings)
end
end
b.report("compact_map_uniq") do
TRY.times do
compact_map_uniq(campaings)
end
end
end
Rehearsal ----------------------------------------------------
each 0.480000 0.000000 0.480000 ( 0.477554)
compact_map_uniq 1.900000 0.010000 1.910000 ( 1.911051)
------------------------------------------- total: 2.390000sec
user system total real
each 0.490000 0.000000 0.490000 ( 0.495289)
compact_map_uniq 1.970000 0.000000 1.970000 ( 1.980382)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment