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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.