Created
February 22, 2023 14:24
-
-
Save jaynetics/3ca24aabc87c43ed6e7e4941102322f3 to your computer and use it in GitHub Desktop.
Ruby benchmark of symbol lookup in case statement vs Hash
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
# results on Ruby 3.2: | |
# | |
# Warming up -------------------------------------- | |
# hash 1.910M i/100ms | |
# case 1.297M i/100ms | |
# Calculating ------------------------------------- | |
# hash 19.029M (± 1.5%) i/s - 95.507M in 5.020123s | |
# case 12.604M (± 0.4%) i/s - 63.534M in 5.040776s | |
# | |
# Comparison: | |
# hash: 19029244.0 i/s | |
# case: 12604156.7 i/s - 1.51x (± 0.00) slower | |
require 'benchmark/ips' | |
arg = :m | |
hash = ('a'..'z').to_h { |c| [c.to_sym, c] } | |
Benchmark.ips do |x| | |
x.report('hash') { hash[arg] } | |
x.report('case') do | |
case arg | |
when :a ; 'a' | |
when :b ; 'b' | |
when :c ; 'c' | |
when :d ; 'd' | |
when :e ; 'e' | |
when :f ; 'f' | |
when :g ; 'g' | |
when :h ; 'h' | |
when :i ; 'i' | |
when :j ; 'j' | |
when :k ; 'k' | |
when :l ; 'l' | |
when :m ; 'm' | |
when :n ; 'n' | |
when :o ; 'o' | |
when :p ; 'p' | |
when :q ; 'q' | |
when :r ; 'r' | |
when :s ; 's' | |
when :t ; 't' | |
when :u ; 'u' | |
when :v ; 'v' | |
when :w ; 'w' | |
when :x ; 'x' | |
when :y ; 'y' | |
when :z ; 'z' | |
end | |
end | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment