From c703c39ae7f5f5e72f0458383a80395d773aed5c Mon Sep 17 00:00:00 2001 From: "T.J. Schuck" Date: Wed, 18 Nov 2015 17:40:58 -0500 Subject: Change Enumerable#sum to use inject(:sym) specification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Not only does this make for simpler, more obvious code, it's also more performant: require 'benchmark/ips' module Enumerable def old_sum(identity = 0, &block) if block_given? map(&block).old_sum(identity) else inject { |sum, element| sum + element } || identity end end def new_sum(identity = 0, &block) if block_given? map(&block).new_sum(identity) else inject(:+) || identity end end end summable = (1..100).to_a # sum is 5050 Benchmark.ips do |x| x.report("old_sum") { summable.old_sum } x.report("new_sum") { summable.new_sum } x.compare! end # Calculating ------------------------------------- # old_sum 10.674k i/100ms # new_sum 14.542k i/100ms # ------------------------------------------------- # old_sum 117.350k (± 7.1%) i/s - 587.070k # new_sum 154.712k (± 3.8%) i/s - 785.268k # # Comparison: # new_sum: 154712.1 i/s # old_sum: 117350.0 i/s - 1.32x slower More benchmarks [here](https://gist.github.com/tjschuck/b3fe4e8c812712376648), including summing strings and passing blocks. The performance gains are less for those, but this version still always wins. --- activesupport/lib/active_support/core_ext/enumerable.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index fc7531d088..8a74ad4d66 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -21,7 +21,7 @@ module Enumerable if block_given? map(&block).sum(identity) else - inject { |sum, element| sum + element } || identity + inject(:+) || identity end end -- cgit v1.2.3