Skip to content

Instantly share code, notes, and snippets.

@pascalbetz pascalbetz/case.rb
Created Feb 10, 2016

Embed
What would you like to do?
Benchmark of Case/If
require 'benchmark/ips'
thing = 102
Benchmark.ips do |x|
x.report('block') do
case thing
when -> (a) { a < 100 && a.even? } then 1
when -> (a) { a > 100 && a.odd? } then 2
else 3
end
end
x.report('if statement') do
if thing < 100 && thing.even?
1
elsif thing > 100 && thing.odd?
2
else
3
end
end
x.report 'without block' do
# NOTE: does not do exactly the same as 'if statement' and 'block'
# just for reference
case thing
when 0..100 then 1
when 100..200 then 2
else 3
end
end
end
Calculating -------------------------------------
block 53.914k i/100ms
if statement 127.066k i/100ms
without block 93.789k i/100ms
-------------------------------------------------
block 904.035k (± 6.4%) i/s - 4.529M
if statement 7.098M (± 8.0%) i/s - 35.324M
without block 2.327M (± 5.7%) i/s - 11.630M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.