fastruby / fast-ruby

:dash: Writing Fast Ruby :heart_eyes: -- Collect Common Ruby idioms.
https://github.com/fastruby/fast-ruby
5.67k stars 376 forks source link

Implement #map#to_h vs #each_with_object #93

Open gogainda opened 8 years ago

gogainda commented 8 years ago

https://medium.com/@vincedevendra/transforming-hashes-which-way-is-best-8f2122577984#.axqpinbeb

kbrock commented 6 years ago

just create a pr for this or close?

mateusdeap commented 1 year ago

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?