Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created April 12, 2022 12:55
Show Gist options
  • Save jodosha/46a53668d3d780040b03b22bded5eb3c to your computer and use it in GitHub Desktop.
Save jodosha/46a53668d3d780040b03b22bded5eb3c to your computer and use it in GitHub Desktop.
Ruby: Compare Hash direct assignment vs merge
#!/usr/bin/env ruby
# frozen_string_literal: true
require "benchmark/ips"
hash1 = {}
hash2 = {}
Benchmark.ips do |x|
x.report("assign") do
hash1["X-Custom"] = "foo"
end
x.report("merge") do
hash2.merge!("X-Custom" => "foo")
end
x.compare!
end
__END__
Results:
Warming up --------------------------------------
assign 1.175M i/100ms
merge 471.783k i/100ms
Calculating -------------------------------------
assign 11.856M (± 3.1%) i/s - 59.904M in 5.058411s
merge 4.719M (± 2.2%) i/s - 23.589M in 5.001957s
Comparison:
assign: 11855616.8 i/s
merge: 4718589.0 i/s - 2.51x (± 0.00) slower
Ruby:
ruby 3.1.0p0 (2021-12-25 revision fb4df44d16) [x86_64-darwin21]
Hardware:
Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro16,2
Processor Name: Quad-Core Intel Core i7
Processor Speed: 2,3 GHz
Number of Processors: 1
Total Number of Cores: 4
L2 Cache (per Core): 512 KB
L3 Cache: 8 MB
Hyper-Threading Technology: Enabled
Memory: 32 GB
System Firmware Version: 1715.81.2.0.0 (iBridge: 19.16.10744.0.0,0)
OS Loader Version: 540.80.2~11
Software:
System Software Overview:
System Version: macOS 12.2.1 (21D62)
Kernel Version: Darwin 21.3.0
Time since boot: 1 day 5:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment