Project

General

Profile

Actions

Patch #34153

closed

Use sum instead of inject(0, :+)

Added by Go MAEDA over 3 years ago. Updated over 3 years ago.

Status:
Closed
Priority:
Normal
Assignee:
Category:
Performance
Target version:
Start date:
Due date:
% Done:

0%

Estimated time:

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).


Files

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

Related issues

Related to Redmine - Feature #34142: Drop Ruby 2.3 supportClosedGo MAEDA

Actions
Actions #1

Updated by Go MAEDA over 3 years ago

Actions #2

Updated by Go MAEDA over 3 years ago

Actions #3

Updated by Go MAEDA over 3 years ago

Actions #4

Updated by Go MAEDA over 3 years ago

  • Target version set to 4.2.0
Actions #5

Updated by Go MAEDA over 3 years ago

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

Committed the patch.

Actions

Also available in: Atom PDF