Last active
January 20, 2019 07:57
-
-
Save iboard/9f447c33b4e14801b903 to your computer and use it in GitHub Desktop.
Benchmarking if versus map-matching (a kind of pattern-matching in ruby)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "benchmark" | |
def log msg | |
# NOOP | |
end | |
def with_if(x) | |
x.times do |n| | |
if (n % 3 == 0) && (n % 5 != 0) | |
log 'Fizz' | |
elsif (n % 3 != 0) && (n % 5 == 0) | |
log 'Buzz' | |
elsif (n % 3 == 0) && (n % 5 == 0) | |
log 'FizzBuzz' | |
else log n | |
end | |
end | |
end | |
def without_if(x) | |
x.times do |n| | |
h = { | |
'Fizz' => (n % 3 == 0) && (n % 5 != 0), | |
'Buzz' => (n % 3 != 0) && (n % 5 == 0), | |
'FizzBuzz' => (n % 3 == 0) && (n % 5 == 0) | |
} | |
log(h.key(true) || n) | |
end | |
end | |
n = 5_000_000 | |
Benchmark.bm(10) do |x| | |
x.report("with if:") { with_if n } | |
x.report("without:") { without_if n } | |
end | |
Restructuring the benchmark to use IPS drops the performance difference from ~5x to ~2.6-2.8x (though without conditionals, there's a much higher variance in individual call performance), so it may perform worse on larger data sets. It's still definitely slower, but maybe less of an outright sacrifice if you're going for the no-conditionals thing.
Calculating -------------------------------------
with if: 41.975k i/100ms
without: 33.080k i/100ms
-------------------------------------------------
with if: 2.712M (± 8.1%) i/s - 13.474M
without: 1.029M (±17.2%) i/s - 4.962M
Comparison:
with if:: 2712057.2 i/s
without:: 1029371.0 i/s - 2.63x slower
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm a CleanCode maniac and love the no-ifs-approach tho ... it's almost 5x slower in this case.
I prefer clean and beauty stuff but sometimes we need brachial brutality 😀