November 17, 2016
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..10).to_a.max
#=> 10
(1..10).to_a.method(:max)
#=> #<Method: Array(Enumerable)#max>
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 .
Benchmark.ips do |bench|
NUM1 = 1_000_000.times.map { rand }
NUM2 = NUM1.dup
ENUM_MAX = Enumerable.instance_method(:max).bind(NUM1)
ARRAY_MAX = Array.instance_method(:max).bind(NUM2)
bench.report('Enumerable#max') do
ENUM_MAX.call
end
bench.report('Array#max') do
ARRAY_MAX.call
end
bench.compare!
end
Warming up --------------------------------------
Enumerable#max 1.000 i/100ms
Array#max 2.000 i/100ms
Calculating -------------------------------------
Enumerable#max 17.569 (± 5.7%) i/s - 88.000 in 5.026996s
Array#max 26.703 (± 3.7%) i/s - 134.000 in 5.032562s
Comparison:
Array#max: 26.7 i/s
Enumerable#max: 17.6 i/s - 1.52x slower
Benchmark.ips do |bench|
NUM1 = 1_000_000.times.map { rand }
NUM2 = NUM1.dup
ENUM_MIN = Enumerable.instance_method(:min).bind(NUM1)
ARRAY_MIN = Array.instance_method(:min).bind(NUM2)
bench.report('Enumerable#min') do
ENUM_MIN.call
end
bench.report('Array#min') do
ARRAY_MIN.call
end
bench.compare!
end
Warming up --------------------------------------
Enumerable#min 1.000 i/100ms
Array#min 2.000 i/100ms
Calculating -------------------------------------
Enumerable#min 18.621 (± 5.4%) i/s - 93.000 in 5.007244s
Array#min 26.902 (± 3.7%) i/s - 136.000 in 5.064815s
Comparison:
Array#min: 26.9 i/s
Enumerable#min: 18.6 i/s - 1.44x slower
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.
If this blog was helpful, check out our full blog archive.