presize/preallocate buckets , change the number of elements, change the perl version, and the winner changes :)
funny bench :)
#!/usr/bin/perl --
use strict; use warnings;
use Benchmark qw/ cmpthese /;
#~ my $cmptime = -abs(shift);
#~ my $cmptime = -3;
my $cmptime = -10;
printf "%10s cmptime %s\n", $], $cmptime;
my @array;
for my $power ( 8, 16,18 ) {
#~ for my $power ( 8, 16, 20, 24 ){
@array = 1 .. ( 2**$power );
print "2 ** $power == @{[int @array ]}\n";
cmpthese(
$cmptime, {
map { ; $_ => __PACKAGE__->can( $_ ) }
qw/ ffor fforc
ifor imap mmap
sffor sfforc sifor simap
slic smap simap2
/
}
);
}
exit;
sub mmap {
my %hash = map { ; $array[$_] => $_ } 0 .. $#array;
();
}
sub imap {
my $ix = 0;
my %hash = map { ; $_ => $ix++ } @array;
();
}
sub slic { my %hash; @hash{@array} = 0 .. $#array; (); }
sub ffor {
my %hash;
for my $ix ( 0 .. $#array ) { $hash{ $array[$ix] } = $ix; }
();
}
sub fforc {
my %hash;
for( my $ix = 0 ; $ix < @array ; $ix++ ) { $hash{ $array[$ix] } =
+$ix; }
();
}
sub ifor {
my %hash;
my $ix = 0;
$hash{$_} = $ix++ for @array;
();
}
## preSize
sub sffor {
my %hash;
keys( %hash ) = int @array;
for my $ix ( 0 .. $#array ) { $hash{ $array[$ix] } = $ix; }
();
}
sub sfforc {
my %hash;
keys( %hash ) = int @array;
for( my $ix = 0 ; $ix < @array ; $ix++ ) { $hash{ $array[$ix] } =
+$ix; }
();
}
sub sifor {
my %hash;
my $ix = 0;
keys( %hash ) = int @array;
$hash{$_} = $ix++ for @array;
();
}
sub smap {
my %hash;
keys( %hash ) = int @array;
@hash{@array} = 0 .. $#array;
();
}
sub simap {
my $i = 0;
my %hash;
keys( %hash ) = int @array;
%hash = map { $_ => $i++ } @array;
();
}
sub simap2 {
my $i = 0;
my %hash;
keys( %hash ) = int @array;
%hash = map(( $_ => $i++ ), @array);
();
}
__END__
funny results :)