--001636c5ac249ccca90493c89354
Content-Type: text/plain; charset=UTF-8

On Fri, Oct 29, 2010 at 11:34 PM, Jeremy Bopp <jeremy / bopp.net> wrote:

> On 10/29/2010 4:28 PM, Ted Flethuseo wrote:
> > I was wondering if a loop of this sort would be
> > effective in ruby for a large number of elements
> >
> >     for i in 1..layers[0].count-1
> >       puts i
> >     end
> >
> > Is it equivalent in efficiency to this?
> >
> > int i  
> > while i < layers[0].count-1
> >    puts i
> > i+> > end
>
> I'm not sure about comparative effectiveness, but this is probably more
> idiomatic:
>
> (layers[0].count - 1).times do |i|
>  puts i+1
> end
>
>
> It's probably also more efficient if only a bit since it does not
> require the creation and evaluation of a Range object.
>
>

int i  ? That's not valid ruby, unless you have a method named int, which
I doubt.

Indeed, a benchmark is the best way to find out. Here's a quick one, with
slight changes to your original code and no puts, and including Jeremy's
idiomatic suggestion.

require 'benchmark'
include Benchmark

Benchmark.benchmark do |bm|
  bm.report("for loop") {
    for i in 1..1_000_000
      i * i
    end
  }

  bm.report("while loop") {
    i  
    while i < 1_000_000
      i * i
      i+    end
  }

  bm.report("times loop") {
    1_000_000.times do |i|
       i * i+1
    end
  }
end

The numbers I got on my machine are:

for loop  1.210000   0.000000   1.210000 (  1.225631)
while loop  1.460000   0.010000   1.470000 (  1.469653)
times loop  1.980000   0.000000   1.980000 (  1.998238)

I expected the times version to be faster too, but it looks like the for
loop is the fastest in this case.

Regards,
Ammar

--001636c5ac249ccca90493c89354--