Replace Range#include? to compare with start and end of range

75 views
Skip to first unread message

Андрей Молчанов

unread,
May 3, 2016, 4:10:09 AM5/3/16
to Ruby on Rails: Core
Hi there,
I propose to replace the use of the method Range#include? to normal compared with the beginning and end of the range.
For example consider the actually used method:
  (11..13).include?(abs_number % 100)
and if we replace him to:
  modulo_number =  abs_number % 100
  modulo_number >= 0) && (modulo_number <= 1)
it increase performance about 1.5 times.

This approach can be used in another real existing place.

Below are the benchmarks data:

Benchmark.ips do |x|
  x.report('old_slow') do
    abs_number = 1234
    (11..13).include?(abs_number % 100)
  end

  x.report('new_fast') do
  abs_number = 1234
  modulo_number = abs_number % 100
  (modulo_number >= 0) && (modulo_number <= 1)
  end

  x.compare!
end
Warming up --------------------------------------
            old_slow   257.215k i/100ms
            new_fast   334.191k i/100ms
Calculating -------------------------------------
            old_slow      5.628M (± 0.9%) i/s -     28.294M in   5.027572s
            new_fast      8.791M (± 0.9%) i/s -     44.113M in   5.018600s

Comparison:
            new_fast:  8790704.5 i/s
            old_slow:  5628188.6 i/s - 1.56x slower

Benchmark.ips do |x|
  x.report('old_slow') do
    x = 0
    (0..1).include?(0)
  end

  x.report('new_fast') do
  x = 0
  (x >= 0) && (x <= 1)
  end

  x.compare!
end
Warming up --------------------------------------
            old_slow   283.858k i/100ms
            new_fast   367.498k i/100ms
Calculating -------------------------------------
            old_slow      6.133M (± 1.3%) i/s -     30.657M in   4.999708s
            new_fast     10.486M (± 1.6%) i/s -     52.552M in   5.012845s

Comparison:
            new_fast: 10486347.5 i/s
            old_slow:  6132780.2 i/s - 1.71x slower

What do you think about it?
Reply all
Reply to author
Forward
0 new messages