In Perl, is a while loop generally faster than a for loop?
- by Mike
I've done a small experiment as will be shown below and it looks like that a while loop is faster than a for loop in Perl. But since the experiment was rather crude, and the subject might be a lot more complicated than it seems, I'd like to hear what you have to say about this.
Thanks as always for any comments/suggestions :)
In the following two small scripts, I've tried while and for loops separately to calcaulte the factorial of 100,000. The one that has the while loop took 57 minutes 17 seconds to finish while the for loop equivalent took 1 hour 7 minutes 54 seconds.
Script that has while loop:
use strict;
use warnings;
use bigint;
my $now = time;
my $n =shift;
my $s=1;
while(1){
$s *=$n;
$n--;
last if $n==2;
}
print $s*$n;
$now = time - $now;
printf("\n\nTotal running time: %02d:%02d:%02d\n\n", int($now / 3600), int(($now % 3600) / 60), int($now % 60));
Script that has for loop:
use strict;
use warnings;
use bigint;
my $now = time;
my $n =shift;
my $s=1;
for (my $i=2; $i<=$n;$i++) {
$s = $s*$i;
}
print $s;
$now = time - $now;
printf("\n\nTotal running time: %02d:%02d:%02d\n\n", int($now / 3600), int(($now % 3600) / 60), int($now % 60));