And adding a third benchmark, using map like the original
under ruby 1.9.2
Rehearsal ----------------------------------------
loop 1.100000 0.140000 1.240000 ( 1.500455)
each 1.060000 0.120000 1.180000 ( 1.430910)
map 1.060000 0.080000 1.140000 ( 1.315434)
------------------------------- total: 3.560000sec
user system total real
loop 1.090000 0.090000 1.180000 ( 1.327022)
each 1.210000 0.100000 1.310000 ( 1.491797)
map 1.080000 0.080000 1.160000 ( 1.288349)
and under 1.8.7
Rehearsal ----------------------------------------
loop 2.950000 0.620000 3.570000 ( 4.199053)
each 3.900000 0.210000 4.110000 ( 4.849201)
map 4.610000 0.110000 4.720000 ( 5.622664)
------------------------------ total: 12.400000sec
user system total real
loop 3.620000 0.200000 3.820000 ( 4.475057)
each 4.760000 0.100000 4.860000 ( 5.561921)
map 4.150000 0.400000 4.550000 ( 5.249561)
ruby for_vs_each.rb 24.21s user 1.69s system 85% cpu 30.320 total
I would note that, since the loop case gives different results, and if
those results aren't the droids you are looking for, then the
performance doesn't really matter. If I don't need to get the correct
results, I can write arbitrarily fast code <G>.
I almost never use for in Ruby, it makes me feel more like I'm writing
C or BASIC, or Algol, or even FORTRAN.
I always keep in mind that the order is 1. Make it run, 2. Make it
right, 3. Make it fast enough, 4. Make it small enough.
1 and 2 are mandatory, 3 and 4 depend on what enough means.
···
On Thu, May 6, 2010 at 5:17 AM, Robert Dober <robert.dober@gmail.com> wrote:
On Wed, May 5, 2010 at 11:50 PM, Mike Austin <mike_ekim@yahoo.com> wrote:
So if a new context is created for every block call in map(), in
theory it should be slower than a for-in loop, correct? I'll have to
try it when I get home.
Mike
No not really (at least for 1.9)
bench.rb · GitHub
here is the output
ruby -v loops.rb
ruby 1.9.1p378 (2010-01-10 revision 26273) [i686-linux]
Rehearsal ----------------------------------------
loop 1.340000 0.000000 1.340000 ( 1.508669)
each 1.340000 0.010000 1.350000 ( 1.388928)
------------------------------- total: 2.690000sec
user system total real
loop 1.380000 0.010000 1.390000 ( 1.419883)
each 1.370000 0.000000 1.370000 ( 1.417870)
ruby -v loops.rb
ruby 1.8.7 (2009-06-12 patchlevel 174) [i486-linux]
Rehearsal ----------------------------------------
loop 3.690000 0.650000 4.340000 ( 4.927702)
each 4.570000 0.770000 5.340000 ( 5.764859)
------------------------------- total: 9.680000sec
user system total real
loop 4.000000 0.630000 4.630000 ( 4.739408)
each 4.510000 0.680000 5.190000 ( 5.489487)
--
Rick DeNatale
Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale