This blog is part of our Ruby 2.4 series.
Ruby has Enumerable#min and Enumerable#max which can be used to find the minimum and the maximum value in an Array.
1 2(1..10).to_a.max 3#=> 10 4(1..10).to_a.method(:max) 5#=> #<Method: Array(Enumerable)#max> 6
Ruby 2.4 adds Array#min and Array#max which are much faster than Enumerable#max and Enuermable#min.
Following benchmark is based on https://blog.blockscore.com/new-features-in-ruby-2-4 .
1Benchmark.ips do |bench| 2 NUM1 = 1_000_000.times.map { rand } 3 NUM2 = NUM1.dup 4 5 ENUM_MAX = Enumerable.instance_method(:max).bind(NUM1) 6 ARRAY_MAX = Array.instance_method(:max).bind(NUM2) 7 8 bench.report('Enumerable#max') do 9 ENUM_MAX.call 10 end 11 12 bench.report('Array#max') do 13 ARRAY_MAX.call 14 end 15 16 bench.compare! 17end 18 19Warming up -------------------------------------- 20 Enumerable#max 1.000 i/100ms 21 Array#max 2.000 i/100ms 22Calculating ------------------------------------- 23 Enumerable#max 17.569 (± 5.7%) i/s - 88.000 in 5.026996s 24 Array#max 26.703 (± 3.7%) i/s - 134.000 in 5.032562s 25 26Comparison: 27 Array#max: 26.7 i/s 28 Enumerable#max: 17.6 i/s - 1.52x slower 29 30Benchmark.ips do |bench| 31 NUM1 = 1_000_000.times.map { rand } 32 NUM2 = NUM1.dup 33 34 ENUM_MIN = Enumerable.instance_method(:min).bind(NUM1) 35 ARRAY_MIN = Array.instance_method(:min).bind(NUM2) 36 37 bench.report('Enumerable#min') do 38 ENUM_MIN.call 39 end 40 41 bench.report('Array#min') do 42 ARRAY_MIN.call 43 end 44 45 bench.compare! 46end 47 48Warming up -------------------------------------- 49 Enumerable#min 1.000 i/100ms 50 Array#min 2.000 i/100ms 51Calculating ------------------------------------- 52 Enumerable#min 18.621 (± 5.4%) i/s - 93.000 in 5.007244s 53 Array#min 26.902 (± 3.7%) i/s - 136.000 in 5.064815s 54 55Comparison: 56 Array#min: 26.9 i/s 57 Enumerable#min: 18.6 i/s - 1.44x slower 58
This benchmark shows that the new methods Array#max and Array#min are about 1.5 times faster than Enumerable#max and Enumerable#min.
Similar to Enumerable#max and Enumerable#min, Array#max and Array#min also assumes that the objects use Comparable mixin to define spaceship <=> operator for comparing the elements.