Patch #34153

Use sum instead of inject(0, :+)

Added by Go MAEDA about 1 month ago. Updated 26 days ago.

Status:ClosedStart date:
Priority:NormalDue date:
Assignee:Go MAEDA% Done:

0%

Category:Performance
Target version:4.2.0

Description

Array#sum introduced in Ruby 2.4 is much faster than Enumerable#inject.

require 'benchmark/ips'

numbers = (1..10).to_a

Benchmark.ips do |x|
  x.report('inject') do
    numbers.inject(0, :+)
  end
  x.report('sum') do
    numbers.sum
  end
  x.compare!
end
Warming up --------------------------------------
              inject   169.646k i/100ms
                 sum   234.947k i/100ms
Calculating -------------------------------------
              inject      1.692M (± 1.7%) i/s -      8.482M in   5.013728s
                 sum      2.347M (± 0.9%) i/s -     11.747M in   5.006572s

Comparison:
                 sum:  2346592.2 i/s
              inject:  1692335.1 i/s - 1.39x  (± 0.00) slower

I have generated the attached patch with rubocop-performance 1.8.1 (Performance/Sum).

use-sum.patch Magnifier (2.43 KB) Go MAEDA, 2020-10-22 11:21


Related issues

Related to Redmine - Feature #34142: Drop Ruby 2.3 support Closed

Associated revisions

Revision 20173
Added by Go MAEDA about 1 month ago

Use sum instead of inject(0, :+) (#34153).

Patch by Go MAEDA.

History

#1 Updated by Go MAEDA about 1 month ago

#2 Updated by Go MAEDA about 1 month ago

#3 Updated by Go MAEDA about 1 month ago

#4 Updated by Go MAEDA about 1 month ago

  • Target version set to 4.2.0

#5 Updated by Go MAEDA about 1 month ago

  • Status changed from New to Closed
  • Assignee set to Go MAEDA

Committed the patch.

Also available in: Atom PDF