From: Ryan Davis Date: 2009-02-21T07:21:34+09:00 Subject: Re: while vs loop On Feb 20, 2009, at 13:57 , Louis-Philippe wrote: > Hi,I saw this thread from last week: while vs loop, > > I don't think anybody mentioned the slight performance difference > between > the two, If you're going to talk performance differences between while and loop, don't forget for and each: > % ./x.rb 1000000 > # of iterations = 1000000 > user system total real > each 0.150000 0.000000 0.150000 ( 0.148313) > for 0.170000 0.000000 0.170000 ( 0.173150) > each-var 0.230000 0.000000 0.230000 ( 0.237410) > while 0.640000 0.010000 0.650000 ( 0.644029) > loop 0.780000 0.000000 0.780000 ( 0.785485) > % ./x.rb 10000000 > # of iterations = 10000000 > user system total real > each 1.370000 0.010000 1.380000 ( 1.380012) > for 1.630000 0.000000 1.630000 ( 1.652562) > each-var 2.450000 0.010000 2.460000 ( 2.479478) > while 5.510000 0.010000 5.520000 ( 5.532909) > loop 7.730000 0.020000 7.750000 ( 7.786959) require 'benchmark' max = (ARGV.shift || 1_000_000).to_i puts "# of iterations = #{max}" Benchmark::bm(20) do |x| x.report("each") do (0..max).each do end end x.report("for") do for i in 0..max do # do nothing end end x.report("each-var") do (0..max).each do |i| end end x.report("while") do n = 0 while true do break if n >= max n += 1 end end x.report("loop") do n = 0 loop do break if n >= max n += 1 end end end