Dear Michael,
None of the above. All your code is calling length() twice per loop.
The best way to write what you want is:
my $max_length = 0;
for my $datum (keys %data) {
my $length = length $datum;
if ($max_length < $length) {
$max_length = $length;
}
}
But there is a faster way:
my $max_length = 0;
while ((my $datum) = each %data) {
my $length = length $datum;
if ($max_length < $length) {
$max_length = $length;
}
}
Benchmarked, it all looks like:
Rate Fifth Fourth Second Third First
Fifth 4539/s -- -46% -53% -57% -58%
Fourth 8333/s 84% -- -14% -21% -24%
Second 9681/s 113% 16% -- -8% -11%
Third 10493/s 131% 26% 8% -- -4%
First 10929/s 141% 31% 13% 4% --
And the benchmark code:
use strict;
use warnings;
use Benchmark ':all';
my %data = (
map { 'x' x rand 100 => undef } 0 .. 1000
);
cmpthese(10000, {
First => sub {
my $max_length = 0;
for my $datum (keys %data) {
$max_length = length($datum) if length($datum) > $max_length;
}
},
Second => sub {
my $max_length = 0;
map { $max_length = ($max_length > length($_) ) ? $max_length
: length($_) }
keys %data;
},
Third => sub {
my $max_length = 0;
map { $max_length = length($_) if length($_) > $max_length }
keys %data;
},
Fourth => sub {
my $max_length = 0;
for my $datum (keys %data) {
my $length = length $datum;
if ($max_length < $length) {
$max_length = $length;
}
}
},
Fifth => sub {
my $max_length = 0;
my $datum;
while (($datum) = each %data) {
my $length = length $datum;
if ($max_length < $length) {
$max_length = $length;
}
}
}
});
__END__
Jonathan Paton
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>