* 7stud -- <bbxx789_05ss / yahoo.com> (21:41) schrieb:

> Don't ever use inject--forget you ever read about it.   Use a hand 
> written loop of your own instead.  Your code will be easier to 
> understand and it will be more efficient.

,----[ /tmp/inject.rb ]
| require 'benchmark'
| 
| s = {}
| range = 1..10_000
| 
| Benchmark.bm(8) do | b |
|   b.report('inject:') { s[:inject] = range.inject(0) { | sum, n | sum + n } }
|   b.report('loop:') do
|     sum = 0
|     for n in range
|       sum += n
|     end
|     s[:loop] = sum
|   end
|   b.report('math:') { s[:math] = ((range.max + 1) * range.max) / 2 - ((range.min - 1) * range.min) / 2 }
| end
| 
| p s
`----

$ ruby1.8 /tmp/inject.rb
              user     system      total        real
inject:   0.130000   0.030000   0.160000 (  0.155900)
loop:     0.060000   0.010000   0.070000 (  0.064232)
math:     0.110000   0.010000   0.120000 (  0.128134)
{:loop=>50005000, :math=>50005000, :inject=>50005000}

$ ruby1.9 /tmp/inject.rb
              user     system      total        real
inject:   0.020000   0.000000   0.020000 (  0.020228)
loop:     0.060000   0.000000   0.060000 (  0.063856)
math:     0.000000   0.000000   0.000000 (  0.000150)
{:loop=>50005000, :math=>50005000, :inject=>50005000}

You are right for Ruby 1.8 (ruby 1.8.5 (2006-08-25) [i486-linux] here),
even math is slower (Bignum I think). But for Ruby 1.9 you are
wrong.

inject is the feature I liked most in Smalltalk.

mfg,                      simon .... l