Open gogainda opened 8 years ago
just create a pr for this or close?
So... I ran this benchmark using ruby 3 and there really wasn't much of a difference. Here's the script I ran:
require 'benchmark/ips'
HASH = { a: 2, b: 3 }
N = 1_000_000
def slow
HASH.map { |k, v| [k, v + 3] }.to_h
end
def fast
HASH.each_with_object({}) { |(k, v), a| a[k] = v + 3 }
end
Benchmark.ips do |x|
x.report('Enumerable#map#to_h') { N.times { slow } }
x.report('Enumerable#each_with_object') { N.times { fast } }
x.compare!
end
And here's the result:
ruby -v code/enumerable/map-to-h-vs-each-with-object.rb 20:34:33
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-darwin20]
Warming up --------------------------------------
Enumerable#map#to_h 1.000 i/100ms
Enumerable#each_with_object
1.000 i/100ms
Calculating -------------------------------------
Enumerable#map#to_h 1.480 (± 0.0%) i/s - 8.000 in 5.406527s
Enumerable#each_with_object
1.584 (± 0.0%) i/s - 8.000 in 5.049983s
Comparison:
Enumerable#each_with_object: 1.6 i/s
Enumerable#map#to_h: 1.5 i/s - 1.07x (± 0.00) slower
So, any sense in still having this?
https://medium.com/@vincedevendra/transforming-hashes-which-way-is-best-8f2122577984#.axqpinbeb