Skip to content

Instantly share code, notes, and snippets.

@cupakromer
Created June 25, 2015 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cupakromer/38a54595ad0ed5ec16ec to your computer and use it in GitHub Desktop.
Save cupakromer/38a54595ad0ed5ec16ec to your computer and use it in GitHub Desktop.
Quad Related Hash lookup benchmarks
require 'benchmark/ips'
substitutions = {
'true' => true,
'false' => false,
'null' => nil,
'' => nil
}.freeze
Benchmark.ips do |x|
x.report("match: fetch") do
token = 'null'.freeze
substitutions.fetch(token, token)
end
x.report("match: fetch-block") do
token = 'null'.freeze
substitutions.fetch(token) { token }
end
x.report("match: lookup") do
token = 'null'.freeze
substitutions.has_key?(token) ? substitutions[token] : token
end
x.report("no match: fetch") do
token = 'no match'.freeze
substitutions.fetch(token, token)
end
x.report("no match: fetch-block") do
token = 'no match'.freeze
substitutions.fetch(token) { token }
end
x.report("no match: lookup") do
token = 'no match'.freeze
substitutions.has_key?(token) ? substitutions[token] : token
end
x.compare!
end
__END__
These benchmarks were taken on a 2012 13-inch MacBook Air:
- OS X Yosemite 10.10.3 (14D136)
- 1.8 GHz Intel Core i5
- 8 GB 1600 MHz DDR3
- Ruby 2.2.2
Perhaps most surprisingly the "no match: lookup" case was the fastest. Followed
by all of the fetch options, with the matched being faster than the
non-matched. Falling in the end was the match with the lookup. The slowest was
the non-matching fetch with a block, which makes sense as the block needs to be
executed in this case.
The match with fecth was about the same irrespective of the block and non-block
form. I speculate this is largely due to this specific data set. Normally the
block defers the cost of whatever it does, while the parameter version needs to
create the value at send time. In this case the lookup is the same as the value
so there is no additional cost.
Calculating -------------------------------------
match: fetch 71.935k i/100ms
match: fetch-block 54.577k i/100ms
match: lookup 70.154k i/100ms
no match: fetch 73.544k i/100ms
no match: fetch-block
68.751k i/100ms
no match: lookup 74.445k i/100ms
-------------------------------------------------
match: fetch 3.760M (±11.6%) i/s - 18.559M
match: fetch-block 3.751M (±12.0%) i/s - 18.447M
match: lookup 3.130M (± 9.7%) i/s - 15.504M
no match: fetch 3.611M (±12.6%) i/s - 17.724M
no match: fetch-block
2.715M (± 8.1%) i/s - 13.475M
no match: lookup 4.123M (±10.4%) i/s - 20.398M
Comparison:
no match: lookup: 4123314.2 i/s
match: fetch: 3759809.8 i/s - 1.10x slower
match: fetch-block: 3751386.4 i/s - 1.10x slower
no match: fetch: 3610654.1 i/s - 1.14x slower
match: lookup: 3129816.3 i/s - 1.32x slower
no match: fetch-block: 2714922.0 i/s - 1.52x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment