Skip to content

Instantly share code, notes, and snippets.

@iboard
Last active January 20, 2019 07:57
Show Gist options
  • Save iboard/9f447c33b4e14801b903 to your computer and use it in GitHub Desktop.
Save iboard/9f447c33b4e14801b903 to your computer and use it in GitHub Desktop.
Benchmarking if versus map-matching (a kind of pattern-matching in ruby)
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
@iboard
Copy link
Author

iboard commented May 1, 2015

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 😀

                 user     system      total        real
with if:     1.470000   0.010000   1.480000 (  1.484849)
without:     7.560000   0.130000   7.690000 (  7.735552)

@blarshk
Copy link

blarshk commented May 1, 2015

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