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 2(1..99).min #=> 1 3(1..99).max #=> 99 4(1..99).minmax #=> [1, 99] 5
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
1 2require 'benchmark/ips' 3 4Benchmark.ips do |bench| 5NUM1 = 1_000_000.times.map { rand } 6 7ENUM_MIN = Enumerable.instance_method(:min).bind(NUM1) 8ENUM_MAX = Enumerable.instance_method(:max).bind(NUM1) 9ENUM_MINMAX = Enumerable.instance_method(:minmax).bind(NUM1) 10 11bench.report('Enumerable#min') do 12ENUM_MIN.call 13end 14 15bench.report('Enumerable#max') do 16ENUM_MAX.call 17end 18 19bench.report('Enumerable#minmax') do 20ENUM_MINMAX.call 21end 22end 23
Results for Ruby 2.3
1 2Warming up -------------------------------------- 3Enumerable#min 1.000 i/100ms 4Enumerable#max 1.000 i/100ms 5Enumerable#minmax 1.000 i/100ms 6Calculating ------------------------------------- 7Enumerable#min 14.810 (±13.5%) i/s - 73.000 in 5.072666s 8Enumerable#max 16.131 (± 6.2%) i/s - 81.000 in 5.052324s 9Enumerable#minmax 11.758 (± 0.0%) i/s - 59.000 in 5.026007s 10
Ruby 2.4
1 2Warming up -------------------------------------- 3Enumerable#min 1.000 i/100ms 4Enumerable#max 1.000 i/100ms 5Enumerable#minmax 1.000 i/100ms 6Calculating ------------------------------------- 7Enumerable#min 18.091 (± 5.5%) i/s - 91.000 in 5.042064s 8Enumerable#max 17.539 (± 5.7%) i/s - 88.000 in 5.030514s 9Enumerable#minmax 13.086 (± 7.6%) i/s - 66.000 in 5.052537s 10
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.