now you can write fast and slower loops in perl. c style loops and
indexing into arrays are slow, perl foreach style loops are fast and
simple. knowing better perl is the way to write better loops, not
listening to anti-perl opinions. ask those naysayers about their 'perl
compatible regex' stuff and watch them stammer about that.
uri
Thanks, Uri. This really helped.
On this note, I referred to perlperf and got this example going:
#!/usr/bin/perl
use warnings;
use strict;
use Benchmark qw
hireswallclock timethese cmpthese);
my $code_C_Style = sub {
my @a = (1..100000);
my $searchfor = 99999;
for (my $i=0; $i <= $#a; $i++) {
last if $a[$i] == $searchfor;
}
};
my $code_Perl_grep = sub {
my @a = (1..100000);
my $searchfor = 99999;
return if grep /$searchfor/, @a;
};
my $code_Perl_foreach = sub {
my @a = (1..100000);
my $searchfor = 99999;
foreach (@a) {
last if /^$searchfor$/;
}
};
my $code_Perl_hashkeys = sub {
my @a = (1..100000);
my $searchfor = 99999;
my %ah;
@ah{@a} = ();
return if exists $ah{$searchfor};
};
my $results = timethese(100, {
C_Style => $code_C_Style,
Perl_grep => $code_Perl_grep,
Perl_foreach => $code_Perl_foreach,
Perl_hashkeys => $code_Perl_hashkeys
}
);
cmpthese($results);
The results were as follows:
Benchmark: timing 100 iterations of C_Style, Perl_foreach, Perl_grep,
Perl_hashkeys...
C_Style: 6.45279 wallclock secs ( 6.36 usr + 0.01 sys = 6.37 CPU)
@ 15.70/s (n=100)
Perl_foreach: 9.16967 wallclock secs ( 8.55 usr + 0.02 sys = 8.57
CPU) @ 11.67/s (n=100)
Perl_grep: 7.02614 wallclock secs ( 6.80 usr + 0.01 sys = 6.81 CPU)
@ 14.68/s (n=100)
Perl_hashkeys: 23.5906 wallclock secs (22.61 usr + 0.04 sys = 22.65
CPU) @ 4.42/s (n=100)
Rate Perl_hashkeys Perl_foreach Perl_grep
C_Style
Perl_hashkeys 4.42/s -- -62%
-70% -72%
Perl_foreach 11.7/s 164% --
-21% -26%
Perl_grep 14.7/s 233% 26%
-- -6%
C_Style 15.7/s 256% 35%
7% --
Looks like the results are against this:
" If you are searching for an element in a list, it can be more
efficient to store the data in a hash structure, and then simply look
to see whether the key is defined, rather than to loop through the
entire array using grep() for instance. " (from perlperf)
Or...did I interpret the results incorrectly, or worse, create the
wrong test case? Pardon me, this is the 1st time I'm venturing into
benchmarking.
Thanks a lot,
Chaitanya