Last active
August 29, 2015 13:58
-
-
Save jamonholmgren/10014780 to your computer and use it in GitHub Desktop.
case-switch-bm.rb
This file contains 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
require 'benchmark' | |
def with_if_else(symbol) | |
if symbol == :success | |
'alert-success' | |
elsif symbol == :error | |
'alert-danger' | |
elsif symbol == :warn | |
'alert-warning' | |
elsif symbol == :info | |
'alert-info' | |
end | |
end | |
def with_case(symbol) | |
case symbol | |
when :success then 'alert-success' | |
when :error then 'alert-danger' | |
when :warn then 'alert-warning' | |
when :info then 'alert-info' | |
end | |
end | |
def with_hash(symbol) | |
{ | |
success: 'alert-success', | |
error: 'alert-danger', | |
warn: 'alert-warning', | |
info: 'alert-info' | |
}[symbol] | |
end | |
puts "If/Else" | |
b = Benchmark.measure do | |
10_000.times do | |
with_if_else :success | |
with_if_else :error | |
with_if_else :warn | |
with_if_else :info | |
end | |
end | |
puts b | |
puts "Case" | |
b = Benchmark.measure do | |
10_000.times do | |
with_case :success | |
with_case :error | |
with_case :warn | |
with_case :info | |
end | |
end | |
puts b | |
puts "Hash lookup" | |
b = Benchmark.measure do | |
10_000.times do | |
with_hash :success | |
with_hash :error | |
with_hash :warn | |
with_hash :info | |
end | |
end | |
puts b |
This file contains 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
ruby case-switch.rb | |
If/Else | |
0.010000 0.000000 0.010000 ( 0.011829) | |
Case | |
0.010000 0.000000 0.010000 ( 0.006596) | |
Hash lookup | |
0.040000 0.000000 0.040000 ( 0.047209) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is using Ruby 2.1.1p76 on OS X.