Ruby 2.4 has optimized Array#min and Array#max methods. Here are some benchmarks.

Ruby 2.4-preview1 was released today.

Up until 2.3, ruby’s Array class took methods from Enumerable mixin which included the #min and #max. Now in 2.4, array has its own min and max methods which are way faster than the old ones. These methods now completely skip the call to Enumerable#each. Ruby maintainers claim it will benificial in big data operations where min/max are the most basic and frequent operations.

Simple script for benchmarking: (using shuffle to remove the chance of algorithm being biased towards sorted arrays)

require 'benchmark'

puts `ruby --version`

a = (1..1_000_000).to_a.shuffle

Benchmark.bm do |x|
  x.report("min:") { 1000.times { a.min } }
  x.report("max:") { 1000.times { a.max } }
end

Running these benchmarks on my macbook air. First on ruby 2.3:

$  ruby ruby_array_min_max_test.rb
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
       user     system      total        real
min: 62.390000   0.110000  62.500000 ( 62.718504)
max: 64.070000   0.400000  64.470000 ( 65.859331)

And now on ruby 2.4.0preview1:

$  ruby ruby_array_min_max_test.rb
ruby 2.4.0preview1 (2016-06-20 trunk 55466) [x86_64-darwin15]
       user     system      total        real
min:  2.450000   0.010000   2.460000 (  2.457457)
max:  2.780000   0.010000   2.790000 (  2.795677)

This is a whopping 20x performace gain!

References: