Actions
Patch #34153
closedUse sum instead of inject(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).
Files
Related issues
Actions