Skip to content

Instantly share code, notes, and snippets.

@myabc
Created December 13, 2011 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save myabc/96ef75f481008a139f8f to your computer and use it in GitHub Desktop.
Save myabc/96ef75f481008a139f8f to your computer and use it in GitHub Desktop.
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
Copy link

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.

@myabc
Copy link
Author

myabc commented Dec 19, 2011

@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