Created
November 2, 2017 15:03
-
-
Save cben/b5edfa8ad7939c9a6d69833394a0a6d1 to your computer and use it in GitHub Desktop.
benchmarking https://github.com/rails/rails/pull/25008
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem 'benchmark-ips' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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