fast-ruby icon indicating copy to clipboard operation
fast-ruby copied to clipboard

Implement #map#to_h vs #each_with_object

Open gogainda opened this issue 9 years ago • 2 comments

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

gogainda avatar Jan 17 '16 17:01 gogainda

just create a pr for this or close?

kbrock avatar Apr 27 '18 15:04 kbrock

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?

mateusdeap avatar Nov 03 '22 23:11 mateusdeap