From: GGarramuno@... (GGarramuno) Date: 2004-01-22T19:50:02+09:00 Subject: Re: New to Python: my impression v. Perl/Ruby Dan Doel wrote in message > We probably shouldn't use #each either, because you can override #each > to mean anything you want. Block creation also seems to be less expensive > than general object creation (or at least range creation), so the > performance > argument is incorrect. > That is indeed interesting! My idea that for loops were faster were taken from some ruby online docs stating that as one of the optimizations to do. I guess that was true of ruby1.6, perhaps. Or the author was just talking about arrays, only. If I turn the range into an array, the iteration itself is faster, thou. It seems for in and by itself is now slow in ruby1.8.1. And an even bigger surprise is to find that a while loop performs the slowest (almost twice as slow now!!!), when it is the one that is not constructing anything but an integer. Hmm... On the positive side, I guess this means there's still quite some room for optimizing these on a future ruby version. def do_times(i) n = 0 i.times do n = n + 1 end end def do_while(i) n = 0 x = 0 while ( x <= i ) n = n + 1 x = x + 1 end end def do_each(i) n = 0 i.each do n = n + 1 end end def do_for2(i) n = 0 for k in i n = n + 1 end end def do_for(i) n = 0 for k in (0..i) n = n + 1 end end max = 10000000 t1 = Time.new do_times max t2 = Time.new puts "#times: ", t2 - t1 do_for max t3 = Time.new puts " for: ", t3 - t2 do_while max t4 = Time.new puts " while: ", t4 - t3 # Construct these without timing it, # just to measure loop itself. # Without turning it into an array, for # is still slower. Maybe ruby iterates # thru ranges internally by turning them into # arrays first? r = (0..max).to_a t5 = Time.new do_for2 r t6 = Time.new puts " for2: ", t6 - t5 do_each r t7 = Time.new puts " each: ", t7 - t6 ######## i got #times: 6.659 for: 6.86 while: 12.097 for2: 6.55 each: 7.44 Hmmm... I found the code for ranges in the ruby source and I sort of understand why this would be so, but I cannot find the for or while entry functions to trace why this could be.