1. 20 11月, 2015 2 次提交
    • K
      Merge pull request #22336 from tjschuck/enumerable_sum_perf · 7e200f29
      Kasper Timm Hansen 提交于
      Change Enumerable#sum to use inject(:sym) specification
      7e200f29
    • T
      Change Enumerable#sum to use inject(:sym) specification · c703c39a
      T.J. Schuck 提交于
      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.
      c703c39a
  2. 19 11月, 2015 10 次提交
  3. 18 11月, 2015 8 次提交
  4. 17 11月, 2015 10 次提交
  5. 16 11月, 2015 9 次提交
  6. 15 11月, 2015 1 次提交