Skip to content

Instantly share code, notes, and snippets.

@asterite
Last active August 29, 2015 13:57
Show Gist options
  • Save asterite/9667066 to your computer and use it in GitHub Desktop.
Save asterite/9667066 to your computer and use it in GitHub Desktop.
type = :info
time = Time.now
2_000_000.times do
msg = case type
when :success then 'alert-success'
when :error then 'alert-danger'
when :warn then 'alert-warning'
when :info then 'alert-info'
end
end
puts "case: #{Time.now - time}"
time = Time.now
2_000_000.times do
msg = if type == :success then 'alert-success'
elsif type == :error then 'alert-danger'
elsif type == :warn then 'alert-warning'
elsif type == :info then 'alert-info'
end
end
puts "if: #{Time.now - time}"
time = Time.now
2_000_000.times do
msg = { success: 'alert-success',
error: 'alert-danger',
notice: 'alert-info',
warn: 'alert-warning' }[type]
end
puts "hash: #{Time.now - time}"
@asterite
Copy link
Author

Time in my machine:

case: 0.291656
if: 0.600187
hash: 2.269872

@jjasonclark
Copy link

Don't need to create a new hash every time. A lookup hash is more like what you had in code.

time = Time.now
msg_lookup = {
    success: 'alert-success',
    error:   'alert-danger',
    notice:  'alert-info',
    warn:    'alert-warning'
}
2_000_000.times do
    msg = msg_lookup[type]
end
puts "hash lookup: #{Time.now - time}"

For me this gives the best result.

case: 0.393963
if: 0.811969
hash: 3.409052
hash lookup: 0.216553

@rohitn
Copy link

rohitn commented Mar 20, 2014

Darwin Kernel Version 13.1.0: Thu Jan 16 19:40:37 PST 2014; root:xnu-2422.90.20~2/RELEASE_X86_64 x86_64 i386 MacBookPro11,3 Darwin

jruby 1.7.10 (1.9.3p392) 2014-01-09 c4ecd6b on Java HotSpot(TM) 64-Bit Server VM 1.7.0_45-b18 [darwin-x86_64]

case: 0.283
if: 0.514
hash: 0.453
hash lookup: 0.133

@jasdeepsingh
Copy link

why allocate hash 2_000_000 times?

@CITguy
Copy link

CITguy commented Mar 21, 2014

Why would a single end user care if it took 2 million iterations to notice roughly a 0.15 second difference between a hash lookup vs a case statement? If the only noticeable difference is readability of the code, I'll stick with a case statement, thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment