------ art_109802_2724214.1157310377165 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 9/3/06, Sander Land <sander.land / gmail.com> wrote: > > On 9/3/06, Phrogz <gavin / refinery.com> wrote: > > Sander Land wrote: > > > class Array > > > def sum > > > inject(0){|a,b| a+b} > > > end > > > end > > > > For a little more speed, try instead: > > > > class Array > > def sum > > inject{ |a,b| a+b } > > end > > end > > Is that really so much faster? Worth breaking on empty arrays? > Just had to test if there was any performance difference, results: > > user system total real > inject(0) 20.320000 5.430000 25.750000 ( 34.486938) > inject 20.450000 5.350000 25.800000 ( 30.152165) > inject &:+ 37.860000 5.690000 43.550000 ( 45.670349) > each 11.130000 3.460000 14.590000 ( 15.042142) > C 0.020000 0.000000 0.020000 ( 0.019815) > > so inject(0) vs inject doesn't really matter. > code: http://pastie.caboo.se/11534 (and yes i know the C code doesn't > handle bignums) > > @Robert: you mean the thread "for performance, write in C" ? ;) Nope not quite :) I forgot the thread, but as far as I remember nobody wanted to hear about "each" I think inject is overused - en vogue - like if it were the only tool for me the code def sum s = 0 each { |e| s += e } s end is robust, readable and rubish, as performance was an issue there was no need to try to be clever and use a *nice* feature like inject. I would use inject e.g. wait, let me see, dunno ;) if performance does not matter of course def sum inject(0){ ... end is the choice, but as you pointed out if you want better performance go *all* the way. Cheers Robert -- Deux choses sont infinies : l'univers et la bóŐise humaine ; en ce qui concerne l'univers, je n'en ai pas acquis la certitude absolue. - Albert Einstein ------ art_109802_2724214.1157310377165--