Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rmm5t
Last active June 18, 2019 20:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmm5t/5e762b0d6cb6edaeb481ea8e26b58b95 to your computer and use it in GitHub Desktop.
Save rmm5t/5e762b0d6cb6edaeb481ea8e26b58b95 to your computer and use it in GitHub Desktop.
Style/MultipleComparison benchmark
require 'benchmark'
def test_conditionals(n)
n == 1 || n == 2 || n == 3 || n == 4 || n == 5 || n == 6 || n == 7
end
def test_include(n)
[1, 2, 3, 4, 5, 6, 7].include?(n)
end
n = 100_000
Benchmark.bmbm(15) do |x|
x.report("conditionals first") { n.times { test_conditionals(1) } }
x.report("Array#include? first") { n.times { test_include(1) } }
x.report("conditionals mid") { n.times { test_conditionals(4) } }
x.report("Array#include? mid") { n.times { test_include(4) } }
x.report("conditionals last") { n.times { test_conditionals(7) } }
x.report("Array#include? last") { n.times { test_include(7) } }
end
# >> user system total real
# >> conditionals first 0.004439 0.000002 0.004441 ( 0.004440)
# >> Array#include? first 0.008101 0.000002 0.008103 ( 0.008103)
# >> conditionals mid 0.006777 0.000000 0.006777 ( 0.006777)
# >> Array#include? mid 0.009760 0.000002 0.009762 ( 0.009761)
# >> conditionals last 0.009099 0.000001 0.009100 ( 0.009100)
# >> Array#include? last 0.011387 0.000002 0.011389 ( 0.011390)
@stevenchanin
Copy link

Dude, you are the man. That's awesome.

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