From: Dan Doel Date: 2004-01-22T06:36:07+09:00 Subject: Re: New to Python: my impression v. Perl/Ruby GGarramuno wrote: >b) i has to be positive for the loop to run > > (-1).times do puts "Foo!" end Produces no output. How is that different from for? (-1).times do a = 0 end puts a Produces an error because a is undefined since the body hasn't been executed, which is a difference from for (where a would be auto-initialized to nil). This is a difference, but one is not noticably more correct than the other. >d) it is more efficient as no blocks are created. > > In "for ..." you need to create a range object 0..i Also, wondering if this is true, I did the following: def do_times(i) n = 0 i.times do n = n + 1 end end def do_for(i) n = 0 for k in (0..i) n = n + 1 end end t1 = Time.new 100000.times do do_times 10 end t2 = Time.new 100000.times do do_for 10 end t3 = Time.new puts "#times: ", t2 - t1 puts " for: ", t3 - t2 Results: #times: 0.982 for: 2.103 So the for method is less efficient (unless I've made an error). >With i.times() I really don't get any of the above. One can asume that i.times >means a loop as it is perhaps a common construct in ruby. >But the truth is that i.times() also leaves room for that behavior to not be >true. It could mean something else, too. It could be a fancy benchmarking >object measuring the following block. Or any object with a times() method, for >that matter. >Pre-assuming it is a loop to me is not as obvious as with a for loop. >And you always get the performance hit of opening a block, which is a big no-no >to me when speed matters. > > 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. - Dan