This blog is part of our Ruby 2.4 series.

Enumerables in Ruby have min, max and minmax comparison methods which are quite convenient to use.

(1..99).min         #=> 1
(1..99).max         #=> 99
(1..99).minmax      #=> [1, 99]

In Ruby 2.4, Enumurable#min, Enumurable#max methods and Enumurable#minmax method are now more optimized.

We would run the following benchmark snippet for both Ruby 2.3 and Ruby 2.4 and observe the results

require 'benchmark/ips'

Benchmark.ips do |bench|
  NUM1 = 1_000_000.times.map { rand }

  ENUM_MIN = Enumerable.instance_method(:min).bind(NUM1)
  ENUM_MAX = Enumerable.instance_method(:max).bind(NUM1)
  ENUM_MINMAX = Enumerable.instance_method(:minmax).bind(NUM1)

  bench.report('Enumerable#min') do
    ENUM_MIN.call
  end

  bench.report('Enumerable#max') do
    ENUM_MAX.call
  end

  bench.report('Enumerable#minmax') do
    ENUM_MINMAX.call
  end
end

Results for Ruby 2.3

Warming up --------------------------------------
      Enumerable#min     1.000  i/100ms
      Enumerable#max     1.000  i/100ms
   Enumerable#minmax     1.000  i/100ms
Calculating -------------------------------------
      Enumerable#min     14.810  (±13.5%) i/s -     73.000  in   5.072666s
      Enumerable#max     16.131  (± 6.2%) i/s -     81.000  in   5.052324s
   Enumerable#minmax     11.758  (± 0.0%) i/s -     59.000  in   5.026007s

Ruby 2.4

Warming up --------------------------------------
      Enumerable#min     1.000  i/100ms
      Enumerable#max     1.000  i/100ms
   Enumerable#minmax     1.000  i/100ms
Calculating -------------------------------------
      Enumerable#min     18.091  (± 5.5%) i/s -     91.000  in   5.042064s
      Enumerable#max     17.539  (± 5.7%) i/s -     88.000  in   5.030514s
   Enumerable#minmax     13.086  (± 7.6%) i/s -     66.000  in   5.052537s

From the above benchmark results, it can be seen that there has been an improvement in the run times for the methods.

Internally Ruby has changed the logic by which objects are compared, which results in these methods being optimized. You can have a look at the commits here and here.