Skip to content

Instantly share code, notes, and snippets.

@sambostock
Last active January 17, 2018 16:34
Show Gist options
  • Save sambostock/d6ddfefad42e441eb82ef962c6ac85a4 to your computer and use it in GitHub Desktop.
Save sambostock/d6ddfefad42e441eb82ef962c6ac85a4 to your computer and use it in GitHub Desktop.
case VS conditional & range VS comparison
Rehearsal ----------------------------------------------------------------
case_comparison 0.690000 0.000000 0.690000 ( 0.702333)
case_range 4.810000 0.020000 4.830000 ( 4.958253)
case_predefined_range 2.880000 0.010000 2.890000 ( 2.933686)
conditional_comparison 0.690000 0.000000 0.690000 ( 0.705765)
conditional_range 4.560000 0.010000 4.570000 ( 4.610029)
conditional_predefined_range 2.730000 0.000000 2.730000 ( 2.771041)
------------------------------------------------------ total: 16.400000sec
user system total real
case_comparison 0.680000 0.000000 0.680000 ( 0.691518)
case_range 4.630000 0.010000 4.640000 ( 4.696290)
case_predefined_range 2.890000 0.000000 2.890000 ( 2.930034)
conditional_comparison 0.680000 0.000000 0.680000 ( 0.691655)
conditional_range 4.450000 0.010000 4.460000 ( 4.500384)
conditional_predefined_range 2.690000 0.010000 2.700000 ( 2.728140)
require 'benchmark'
N = 10_000_000
NUMBERS = N.times
LOWER_BOUND = N / 3
UPPER_BOUND = LOWER_BOUND * 2
UPPER_RANGE = UPPER_BOUND...Float::INFINITY
LOWER_RANGE = 0...LOWER_BOUND
def case_comparison(n)
case
when n >= UPPER_BOUND
3
when n < LOWER_BOUND
1
else
2
end
end
def case_range(n)
case n
when UPPER_BOUND...Float::INFINITY
3
when 0...LOWER_BOUND
1
else
2
end
end
def case_predefined_range(n)
case n
when UPPER_RANGE
3
when LOWER_RANGE
1
else
2
end
end
def conditional_comparison(n)
if n >= UPPER_BOUND
3
elsif n < LOWER_BOUND
1
else
2
end
end
def conditional_range(n)
if (UPPER_BOUND...Float::INFINITY) === n
3
elsif (0...LOWER_BOUND) === n
1
else
2
end
end
def conditional_predefined_range(n)
if UPPER_RANGE === n
3
elsif LOWER_RANGE === n
1
else
2
end
end
Benchmark.bmbm do |x|
x.report('case_comparison') { NUMBERS.each { |n| case_comparison(n) } }
x.report('case_range') { NUMBERS.each { |n| case_range(n) } }
x.report('case_predefined_range') { NUMBERS.each { |n| case_predefined_range(n) } }
x.report('conditional_comparison') { NUMBERS.each { |n| conditional_comparison(n) } }
x.report('conditional_range') { NUMBERS.each { |n| conditional_range(n) } }
x.report('conditional_predefined_range') { NUMBERS.each { |n| conditional_predefined_range(n) } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment