Skip to content

Instantly share code, notes, and snippets.

@okuramasafumi
Created August 11, 2022 10:01
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 okuramasafumi/9332babda9be4f1bba81750df4fad145 to your computer and use it in GitHub Desktop.
Save okuramasafumi/9332babda9be4f1bba81750df4fad145 to your computer and use it in GitHub Desktop.
Performance comparison between hash lookup and case lookup
MAPPING = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
}.freeze
def method1(key)
MAPPING[key]
end
def method2(key)
case key
when :a then 1
when :b then 2
when :c then 3
when :d then 4
when :e then 5
when :f then 6
end
end
def method3(key)
mapping = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
}
mapping[key]
end
require 'benchmark/ips'
Benchmark.ips do |x|
x.report('method1') { method1(:f) }
x.report('method2') { method2(:f) }
x.report('method3') { method3(:f) }
x.compare!
end
__END__
Warming up --------------------------------------
method1 1.409M i/100ms
method2 1.403M i/100ms
method3 785.691k i/100ms
Calculating -------------------------------------
method1 14.498M (± 1.4%) i/s - 73.245M in 5.053246s
method2 14.113M (± 3.7%) i/s - 71.536M in 5.076314s
method3 8.912M (±10.1%) i/s - 43.999M in 5.052516s
Comparison:
method1: 14497516.1 i/s
method2: 14112908.5 i/s - same-ish: difference falls within error
method3: 8911587.0 i/s - 1.63x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment