diff options
author | T.J. Schuck <tj@getharvest.com> | 2015-11-18 17:40:58 -0500 |
---|---|---|
committer | T.J. Schuck <tj@getharvest.com> | 2015-11-19 11:09:03 -0500 |
commit | c703c39ae7f5f5e72f0458383a80395d773aed5c (patch) | |
tree | 154fa209104075f9c9b8fef7d3b433345b4d2181 /activesupport/lib | |
parent | 3d8a7c0e64fef726c22fd64911771cee8c467447 (diff) | |
download | rails-c703c39ae7f5f5e72f0458383a80395d773aed5c.tar.gz rails-c703c39ae7f5f5e72f0458383a80395d773aed5c.tar.bz2 rails-c703c39ae7f5f5e72f0458383a80395d773aed5c.zip |
Change Enumerable#sum to use inject(:sym) specification
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.
Diffstat (limited to 'activesupport/lib')
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 2 |
1 files changed, 1 insertions, 1 deletions
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 |