Created
June 3, 2015 17:12
-
-
Save huned/89c44bcfd76f1add3b31 to your computer and use it in GitHub Desktop.
`inject(:+)` vs `each +=`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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