Created
September 18, 2023 04:04
-
-
Save postmodern/3797e1c265bebad952cbe9aef9589d65 to your computer and use it in GitHub Desktop.
Micro-benchmark to test `||=` and `[]=` vs. explicit initialize xor `[]=`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'benchmark' | |
keys = ('aa'..'zz').map(&:to_sym) | |
Benchmark.bm do |b| | |
n = 10_000 | |
b.report('lazy initialize') do | |
n.times do | |
hash = nil | |
keys.each do |key| | |
hash ||= {} | |
hash[key] = 1 | |
end | |
end | |
end | |
b.report('explicit initialize') do | |
n.times do | |
hash = nil | |
keys.each do |key| | |
if hash | |
hash[key] = 1 | |
else | |
hash = {key => 1} | |
end | |
end | |
end | |
end | |
end |
Author
postmodern
commented
Sep 18, 2023
IMHO, it's not fair when comparing that way.
In the lazy initialize
part, should we change it to below instead?
(since we need to initialize the hash with the default key
rather than an empty hash
.)
n.times do
hash = nil
keys.each do |key|
hash ||= {key: 1}
end
end
Agree to @sanG-github Nope, that would then only set the very first key.
Alternative:
else # !hash
hash = {}
hash[key] = 1
end
In my case, doesnt have much effect on the benchmark results, though.
Quicker implementation in my short tests is
b.report('explicit initialize, always assign') do
n.times do
hash = nil
keys.each do |key|
if !hash
hash = {}
end
hash[key] = 1
end
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment