--0016e6d9a3e8fcd3c1046360a4cd
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit

Hi,I saw this thread from last week: while vs loop,

I don't think anybody mentioned the slight performance difference between
the two,
(or maybe I got the wrong info!!)
In fact, I had always assumed the 'loop do' construct to be better than
'while 1 do', if only to be more elegant or concise for implementing
infinite loops... but it turns out it seems to be the other way:

##############
require 'benchmark'
Benchmark.bm do |x|
 x.report('while1') do
n  
while 1 do
break if n > 0000000
n + 
end
end
 x.report('loop  ') do
n  
loop do
break if n > 0000000
n + 
end
end
end

##############
RESULTS:

                   user     system      total        real
while 1 19.770000   0.230000  20.000000 ( 34.458926)
loop     25.870000   0.300000  26.170000 ( 42.804569)

###########

I'm running this benchmark on 1.8.6 patchlevel 114 (universal-darwin9.0)

So why is it behaving this way?
Are every implementations doing the same?

Thanks!

L-P





On Sat, Feb 14, 2009 at 7:16 AM, Nobuyoshi Nakada
<n...<http://groups.google.com/groups/unlock?_doneroup/ruby-talk-google/browse_thread/thread/3ee74ef131ec90ba&msg/988b0deb69e61d>
@ruby-lang.org> wrote:
> Hi,

> At Sat, 14 Feb 2009 15:03:03 +0900,
> Vetrivel Vetrivel wrote in [ruby-talk:328175]:
>> what is the Difference between loop and while in ruby ?

>> loop do
>> end

> loop is a kernel method which takes a block.  A block
> introduces new local variable scope.

>  loop do
>    a  
>    break
>  end
>  p a #causes NameError

>> while 1
>> end

> while doesn't.

>  while 1
>    a  
>    break
>  end
>  p a #1

> --
> Nobu Nakada

furthermore loop do has an implicit rescue clause for a StopIteration
exception
(I believe 1.8.7 and 1.9.1 only IIRC)

therefore

loop do
   some_enumerator.next
end
becomes a convenient idiom.

HTH
Robert

--0016e6d9a3e8fcd3c1046360a4cd--