Skip to content

Instantly share code, notes, and snippets.

@cben
Created November 2, 2017 15:03
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 cben/b5edfa8ad7939c9a6d69833394a0a6d1 to your computer and use it in GitHub Desktop.
Save cben/b5edfa8ad7939c9a6d69833394a0a6d1 to your computer and use it in GitHub Desktop.
gem 'benchmark-ips'
require 'benchmark/ips'
module Enumerable
# current behaviour
def index_by
if block_given?
Hash[map { |elem| [yield(elem), elem] }]
else
to_enum(:index_by) { size if respond_to?(:size) }
end
end
# new behaviour
def index_by2
if block_given?
result = {}
each {|elem| result[yield(elem)] = elem }
result
else
to_enum(:index_by) { size if respond_to?(:size) }
end
end
end
ExpandedPayment = Struct.new(:dollars, :cents)
arr = (1..100000).map do
# edit first random range to control approx number of distinct keys
ExpandedPayment.new(Random.rand(1..100), Random.rand(0..999))
end
Benchmark.ips do |x|
x.report('before') { arr.index_by(&:dollars) }
x.report('after') { arr.index_by2(&:dollars) }
x.compare!
end
puts "#{arr.size} items, #{arr.index_by(&:dollars).size} unique"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment