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
Updated by Go MAEDA about 4 years ago
- Related to Feature #25048: Ruby 2.4 support added
Updated by Go MAEDA about 4 years ago
- Related to Feature #34142: Drop Ruby 2.3 support added
Updated by Go MAEDA about 4 years ago
- Related to deleted (Feature #25048: Ruby 2.4 support)
Updated by Go MAEDA about 4 years ago
- Status changed from New to Closed
- Assignee set to Go MAEDA
Committed the patch.
Actions