From: oldgeezer <[EMAIL PROTECTED]>
> What I would like to understand is why looping
> 2 times through 5000 lines takes less time than
> looping 5000 times through 2 lines.
> 
> To show what I mean, I wrote a snippet that
> does nothing with the data and yet the first
> part is 5 times faster than the second part
> (in my pc anyway).
> 
> Thanks.
> Rob.
> 
> 
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> use POSIX qw(clock);
> 
> #just create a small array for this test
> my @few=();
> for my $i(1...2){push @few, $i};
> 
> #just create a big array for this test
> my @many=();
> for my $i(1...500000){push @many, $i};

Even though there is an optimization for this type of for() 
statements, the (1..500000) is not a part of the for() syntax, it's a 
list generator that may be used anywhere. So you can create the array 
like this:

  my @many=(1..500000);

(In this case .. and ... work exactly the same.)

> # part 1, loop few times over much data
> my $time_1=clock();
> foreach my $val (@few){
>     foreach my $other(@many) {} #do zilch
> }

How many times do you create a new iteration variable and too 
whatever setup work is necessary for the for() loop? 3 times, right?

> # part 2, loop many times over few data
> my $time_3=clock();
> foreach my $val (@many){
>     foreach my $other(@few) {} #do zilch
> }

And how many times in this case?
1+500000 times!

In either case ... do not worry. Most likely the difference will be 
totally unimportant. Usualy the difference of the sizes is nowhere 
this dramatic and you do not do zilch inside the loop so whatever 
difference there is will be insignificant compared to the the time 
you spend actually doing something.

Everything else equal it may be better to loop through the longer 
list in the outer for(), but I would not sweat over it.

"Premature optimization is the root of all evil." :-)

Jenda
===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to