Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement #map#to_h vs #each_with_object #93

Open
gogainda opened this issue Jan 17, 2016 · 2 comments
Open

Implement #map#to_h vs #each_with_object #93

gogainda opened this issue Jan 17, 2016 · 2 comments

Comments

@gogainda
Copy link

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

@kbrock
Copy link
Contributor

kbrock commented Apr 27, 2018

just create a pr for this or close?

@mateusdeap
Copy link
Member

mateusdeap commented Nov 3, 2022

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants