-
-
Save myabc/96ef75f481008a139f8f to your computer and use it in GitHub Desktop.
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' | |
module Helper1 | |
def twitterized_type(type) | |
case type | |
when :alert | |
"warning" | |
when :error | |
"error" | |
when :notice | |
"info" | |
when :success | |
"success" | |
else | |
type.to_s | |
end | |
end | |
module_function :twitterized_type | |
end | |
module Helper2 | |
def twitterized_type(type) | |
{ | |
alert: 'warning', | |
error: 'error', | |
notice: 'info', | |
success: 'success' | |
}.fetch(type, type.to_s) | |
end | |
module_function :twitterized_type | |
end | |
module Helper3 | |
def twitterized_type(type) | |
{ | |
alert: 'warning', | |
error: 'error', | |
notice: 'info', | |
success: 'success' | |
}[type] || type.to_s | |
end | |
module_function :twitterized_type | |
end | |
n = 500000 | |
Benchmark.bm(7) do |x| | |
x.report('case statement') { n.times { |i| Helper1.twitterized_type(:success) } } | |
x.report('hash lookup ') { n.times { |i| Helper2.twitterized_type(:success) } } | |
x.report('hash lookup 2 ') { n.times { |i| Helper3.twitterized_type(:success) } } | |
x.report('when not exist: case statement') { n.times { |i| Helper1.twitterized_type(:non_existent) } } | |
x.report('when not exist: hash lookup ') { n.times { |i| Helper2.twitterized_type(:non_existent) } } | |
x.report('when not exist: hash lookup 2 ') { n.times { |i| Helper3.twitterized_type(:non_existent) } } | |
end |
@amalagaura Thanks. Of course, I should have memoized the hash (or used a constant). It makes a significant difference when I run the benchmark again. I think case statements will always be faster – there is still one fewer Hash object being created.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to create the hash just once, check out my fork, it is almost the same speed, but surprisingly still not as fast as the case.