Skip to content

Instantly share code, notes, and snippets.

@danielevans
Created February 1, 2017 08:46
Show Gist options
  • Save danielevans/53610ccba01c3f586ac0869adb55c182 to your computer and use it in GitHub Desktop.
Save danielevans/53610ccba01c3f586ac0869adb55c182 to your computer and use it in GitHub Desktop.
# user system total real
# case 0.050000 0.000000 0.050000 ( 0.059868)
# if 0.090000 0.000000 0.090000 ( 0.091604)
# hash 0.070000 0.000000 0.070000 ( 0.081646)
# bad hash 0.690000 0.020000 0.710000 ( 0.709891)
require 'benchmark'
iterations = 1_000_000
HASH = { 1 => 1, 2 => 2, 3 => 3, 4 => 4 }
Benchmark.bm(16) do |bm|
bm.report 'case' do
iterations.times do |i|
case i
when 1
@x = 1
when 2
@x = 2
when 3
@x = 3
when 4
@x = 4
end
end
end
bm.report 'if' do
iterations.times do |i|
if i == 1
@x = 1
elsif i == 2
@x = 2
elsif i == 3
@x = 3
elsif i == 4
@x = 4
end
end
end
bm.report 'hash' do
iterations.times do |i|
if HASH[i]
@x = HASH[i]
end
end
end
bm.report 'bad hash' do
iterations.times do |i|
hash = { 1 => 1, 2 => 2, 3 => 3, 4 => 4 }
if hash[i]
@x = hash[i]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment