Skip to content

Instantly share code, notes, and snippets.

@huned
Created June 3, 2015 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huned/89c44bcfd76f1add3b31 to your computer and use it in GitHub Desktop.
Save huned/89c44bcfd76f1add3b31 to your computer and use it in GitHub Desktop.
`inject(:+)` vs `each +=`
irb(main):003:0> require 'benchmark'
=> true
irb(main):004:0> numbers = nil
=> nil
irb(main):005:0> puts Benchmark.measure { numbers = 1_000_000.times.map {|i| i.to_f }; 1 }
1.110000 0.000000 1.110000 ( 0.448476)
=> nil
irb(main):006:0> numbers.length
=> 1000000
irb(main):007:0> puts Benchmark.measure { numbers.inject(:+) }
0.070000 0.000000 0.070000 ( 0.060648)
=> nil
irb(main):008:0> puts Benchmark.measure { s = 0; numbers.each {|n| s += n } }
0.820000 0.010000 0.830000 ( 0.587285)
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment