b1 = Time.now
puts (1..100000).inject(0) { |x, y| x + y }
a1 = Time.now
puts "Time for inject: #{a1 - b1}"
b2 = Time.now
sum = 0
(1..100000).each do |value|
sum += value
end
puts sum
a2 = Time.now
puts "Time for each: #{a2 - b2}"
The above Ruby code compares two ways of summing up integers. To my surprise, the more elegant inject or reduce approach is outperformed by the other. Why is that the case? Why do people bother using the inefficient inject or reduce? Simply because it’s elegant?
PS: Thanks for all the inspiring answers. My intention was to ask what’s going on behind the scene that results in the differences.
I would go with a little math in this case:
And the result is:
A better math is always faster 🙂