Permalink
Browse files

Pass a symbol instead of a block. This is faster and more concise.

At least Ruby 1.8.7 is required which is ok since 3.2.

Benchmark:

```ruby
require "benchmark"

enum = 1..10_000
N = 100
Benchmark.bm do |x|
  x.report "inject block" do
    N.times do
      enum.inject { |sum, n| sum + n }
    end
  end

  x.report "inject symbol" do
    N.times do
      enum.inject(:+)
    end
  end
end
```

Result:

```
       user     system      total        real
inject block   0.160000   0.000000   0.160000 (  0.179723)
inject symbol  0.090000   0.000000   0.090000 (  0.095667)
```
  • Loading branch information...
1 parent 78ef738 commit d696f8de92ceb3cb38b11ec3b200b082b9578742 @semaperepelitsa semaperepelitsa committed Jan 15, 2012
Showing with 1 addition and 1 deletion.
  1. +1 −1 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -59,7 +59,7 @@ def sum(identity = 0, &block)
if block_given?
map(&block).sum(identity)
else
- inject { |sum, element| sum + element } || identity
+ inject(:+) || identity
end
end

0 comments on commit d696f8d

Please sign in to comment.