vadviktor
9/30/2015 - 3:27 PM

Ruby range vs plain compare

Ruby range vs plain compare

Calculating -------------------------------------
        range#cover?   131.362k i/100ms
      range#include?   132.367k i/100ms
       range#member?   133.159k i/100ms
       plain compare   150.620k i/100ms
-------------------------------------------------
        range#cover?      4.969M (± 5.5%) i/s -     24.827M
      range#include?      4.894M (± 6.9%) i/s -     24.356M
       range#member?      4.935M (± 5.4%) i/s -     24.634M
       plain compare      8.566M (± 7.6%) i/s -     42.475M

Comparison:
       plain compare:  8566176.8 i/s
        range#cover?:  4968558.2 i/s - 1.72x slower
       range#member?:  4934557.4 i/s - 1.74x slower
      range#include?:  4894043.0 i/s - 1.75x slower
require 'benchmark/ips'

Benchmark.ips do |x|
  x.report('range#cover?') { (91..179).cover? 100 }
  x.report('range#include?') { (91..179).include? 100 }
  x.report('range#member?') { (91..179).member? 100 }
  x.report('plain compare') { 91 < 100 && 100 < 179 }

  x.compare!
end