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

Fast Ruby for hash_update_vs_hash_brackets #194

Open
manjunath724 opened this issue Aug 6, 2021 · 0 comments
Open

Fast Ruby for hash_update_vs_hash_brackets #194

manjunath724 opened this issue Aug 6, 2021 · 0 comments

Comments

@manjunath724
Copy link

manjunath724 commented Aug 6, 2021

Hash#update is an alias for Hash#merge!

Currently we have merge_bang_vs_[]= which suggests that Hash#[]= is faster and Hash#merge!() is slower.
But we dont have any suggestions for update_vs_[]= i.e., Hash#update() vs Hash#[]=.

require 'benchmark/ips'

ENUM = (1..100)

def fast
  ENUM.each_with_object({}) do |e, h|
    h[e] = e
  end
end

def slow
  ENUM.each_with_object({}) do |e, h|
    h.update(e => e)
  end
end

Benchmark.ips do |x|
  x.report('Hash#[]=') { fast }
  x.report('Hash#update') { slow }
  x.compare!
end
##### `Hash#update` vs `Hash#[]=` [code](code/hash/update-vs-\[\]=.rb)

$ ruby -v code/hash/update-vs-\[\]=.rb
ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-darwin18]

Warming up --------------------------------------
            Hash#[]=     7.453k i/100ms
         Hash#update     4.311k i/100ms
Calculating -------------------------------------
            Hash#[]=     74.764k (± 1.9%) i/s -    380.103k in   5.085962s
         Hash#update     43.220k (± 0.8%) i/s -    219.861k in   5.087364s

Comparison:
            Hash#[]=:    74764.0 i/s
         Hash#update:    43220.1 i/s - 1.73x  (± 0.00) slower

Can we extend this to Hash#update()?

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

No branches or pull requests

2 participants