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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Agree to @sanG-githubNope, that would then only set the very first key.Alternative:
In my case, doesnt have much effect on the benchmark results, though.
Quicker implementation in my short tests is