Issue #13437 has been reported by watson1978 (Shizuo Fujita).

----------------------------------------
Bug #13437: Improve performance of Enumerable#{sort_by,min_by,max_by,minmax_by}
https://bugs.ruby-lang.org/issues/13437

* Author: watson1978 (Shizuo Fujita)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: 
* Backport: 2.2: UNKNOWN, 2.3: UNKNOWN, 2.4: UNKNOWN
----------------------------------------
Improve performance of Enumerable#{sort_by,min_by,max_by,minmax_by}

### Before
~~~
                user     system      total        real
sort_by     1.810000   0.010000   1.820000 (  1.824355)
min_by(n)   2.530000   0.000000   2.530000 (  2.534154)
min_by      2.450000   0.000000   2.450000 (  2.456396)
max_by(n)   3.240000   0.000000   3.240000 (  3.238680)
max_by      2.440000   0.010000   2.450000 (  2.444972)
minmax_by   3.080000   0.000000   3.080000 (  3.083867)
~~~

### After
~~~
                user     system      total        real
sort_by     1.100000   0.020000   1.120000 (  1.122831)
min_by(n)   1.650000   0.000000   1.650000 (  1.657220)
min_by      1.600000   0.010000   1.610000 (  1.625084)
max_by(n)   1.930000   0.010000   1.940000 (  1.953623)
max_by      1.630000   0.010000   1.640000 (  1.639236)
minmax_by   1.760000   0.000000   1.760000 (  1.759928)
~~~

### Test code
~~~
require 'benchmark'

Benchmark.bmbm do |x|

  enum = (1..1000).to_a.each

  x.report "sort_by" do
    10000.times do
      enum.sort_by { |a| a }
    end
  end

  x.report "min_by(n)" do
    20000.times do
      enum.min_by(2) { |a| a }
    end
  end

  x.report "min_by" do
    20000.times do
      enum.min_by { |a| a }
    end
  end

  x.report "max_by(n)" do
    10000.times do
      enum.max_by(2) { |a| a }
    end
  end

  x.report "max_by" do
    20000.times do
      enum.max_by { |a| a }
    end
  end

  x.report "minmax_by" do
    20000.times do
      enum.minmax_by { |a| a }
    end
  end

end
~~~

### Patch
https://github.com/ruby/ruby/pull/1584



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>