From: Josh Cheek Date: 2010-11-01T01:39:50+09:00 Subject: Re: Is this an effective loop --0015175cdff80598d60493ec57ae Content-Type: text/plain; charset=ISO-8859-1 On Sun, Oct 31, 2010 at 5:15 AM, Robert Klemme wrote: > > Regardless, the big thing we see is that the loops all perform roughly >> equivalently overall. Their relative differences in overhead will >> likely be dwarfed by the looped operations in the real world. >> > > Agreed. > > FWIW, on mine they were not close. The while loop was much faster on every implementation except MRI 1.8.6 and 1.8.7 I used your benchmark, except switched bmbm with just bm, for readability of output (the results were not significantly different). http://gist.github.com/656788 I don't know how to take that, I would have expected while loop to be significantly slower than all of the rest. Also, interestingly, check out Macruby! Peter Cooper wrote an article about it recently, I think I'll go re-read it. > for i in 1..layers[0].count-1 >> puts i >> end >> >> Is it equivalent in efficiency to this? >> >> int i = 1 >> while i < layers[0].count-1 >> puts i >> i+=1 >> end >> > > The answer is no because the second one does one less iteration. :-) > > Also, the top one calculates layers[0].count-1 only once. The bottom one re-evaluates that expression every time. That makes the bottom one less efficient (I am truly stunned that it won the benchmarks so thoroughly), and could also mean they behave differently depending on what you do in the loop. layers = [1,2,3,4,5] for i in 1..(puts "FOR LOOP"; layers.size-1) end i = 1 while i < (puts "WHILE LOOP"; layers.size-1) i+=1 end --0015175cdff80598d60493ec57ae--