---
title: "Ruby 2.4 has optimized enumerable min max methods"
description:
  "min, max and minmax methods for enumerable class have been optimized in ruby
  2.4"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-4-0-has-optimized-enumerable-min-max-methods"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-4-0-has-optimized-enumerable-min-max-methods.md"
---

# Ruby 2.4 has optimized enumerable min max methods

min, max and minmax methods for enumerable class have been optimized in ruby 2.4

- Author: Chirag Shah
- Published: September 28, 2017
- Categories: Ruby 2.4, Ruby

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

```ruby

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

```

In Ruby 2.4, `Enumurable#min`, `Enumurable#max`
[methods](https://github.com/ruby/ruby/commit/3dcd4b2a98e) and
`Enumurable#minmax` [method](https://github.com/ruby/ruby/commit/9f44b77a18d)
are now more optimized.

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

```ruby

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

```ruby

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

```ruby

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](https://github.com/ruby/ruby/commit/9f44b77a18d) and
[here](https://github.com/ruby/ruby/commit/3dcd4b2a98e).

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-4-0-has-optimized-enumerable-min-max-methods)
