#!/usr/bin/perl
use warnings;
use strict;
use Benchmark 'cmpthese';
my @k = qw( 1 2 3 4 5 6 );
cmpthese( -10, {
exists => sub {
my $count = 0;
my %hash;
@hash{ @k } = ();
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if exists $hash{ $num };
}
return $count;
},
hash => sub {
my $count = 0;
my %hash = map { $_ => 1 } @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if $hash{ $num };
}
return $count;
},
grep_r => sub {
my $count = 0;
my @array = @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if grep /^$num$/, @array;
}
return $count;
},
grep_e => sub {
my $count = 0;
my @array = @k;
for my $num ( 1, 3, 5, 7, 9, 11 ) {
$count++ if grep $_ == $num, @array;
}
return $count;
},
} );
Produces the result (on my computer):
Rate grep_r grep_e hash exists
grep_r 4838/s -- -81% -83% -90%
grep_e 25923/s 436% -- -10% -49%
hash 28848/s 496% 11% -- -43%
exists 50524/s 944% 95% 75% --
So in my test exists() is definitely faster.
Awesome, definately soemthing for me to look into, thanks a bunch John!
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>