Update: Reran and posted results from matching Perl versions: perl-5.24.2 and cperl-5.24.2c.
Update: Added results from Perl 5.26.0 for comparison.
Hi karlgoethebier,
With little change, the code can run just as fast.
use strict;
use warnings;
use Data::Dump qw(pp);
use feature qw(say);
my @points = map { pp($_) } (
[ 0, 0 ],
[ -1, -2 ],
[ 1, 2 ],
[ -1, 2 ],
[ 1, -2 ],
[ 0, 1 ],
[ 1, 0 ],
[ -1, 0 ],
[ 0, -1 ],
[ 2147483647, 2147483647 ],
[ 2147483647, -2147483647 ],
[ -2147483647, 2147483647 ],
[ -2147483647, -2147483647 ],
);
kgb_str_look( kgb_str_hash() );
sub kgb_str_hash {
my %cells = map { $_ => undef } @points;
\%cells;
}
sub kgb_str_look {
my $cells = shift;
for (@points) {
( exists $cells->{$_} ) ? say $_ : die;
}
}
In the spirit of fun, added kgb to the test script. The mat_hash was updated to safeguard from auto-vivification. See this post.
use Data::Dump qw(pp);
sub kgb_hash {
my %cells = map { pp($_) => undef } @points;
\%cells;
}
{
my @points_str;
sub kgb_look {
my $cells = shift;
unless (@points_str) {
for my $p (@points) {
push @points_str, pp($p);
}
}
for my $p (@points_str) {
exists $cells->{$p} or die;
}
exists $cells->{'notfound'} and die;
exists $cells->{'notfound2'} and die;
exists $cells->{'notfound3'} and die;
}
}
my $kgb_ref = kgb_hash();
...
timethese 200000, {
Big => sub { big_look($big_ref) }, # $cells->{ ($p->[1] << 32) | ($
+p->[0] & 0xFFFFFFFF) }
Kgb => sub { kgb_look($kgb_ref) }, # $cells->{ $str } # optimized
Lan => sub { lan_look($lan_ref) }, # $cells->{ "@$p" }
Mat => sub { mat_look($mat_ref) }, # $cells->{ $_->[0] }{ $_->[1] }
Pak => sub { pak_look($pak_ref) }, # $cells->{ pack "ii", $p->[0],
+$p->[1] }
St2 => sub { st2_look($st2_ref) }, # $cells->{ join(':', @$p) }
St3 => sub { st3_look($st3_ref) }, # $cells->{ $str } # optimized
Str => sub { str_look($str_ref) }, # $cells->{ $p->[0] .':'. $p->[1
+] }
};
Results obtained from a Mac laptop running at 2.6 GHz, comparing perl-5.24.2 against cperl-5.24.2c.
Results from Perl 5.26.0 for comparison.
For some reason, the state feature doesn't support initialization in list context.
sub kgb_look {
my $cells = shift;
state @points_str = map { pp($_) } @points;
...
}
Initialization of state variables in list context currently forbidden
+at test.pl line 341, near "@points;"
Execution of test.pl aborted due to compilation errors.
Alrighty, state initialization works fine for an anonymous array.
use feature qw(state);
sub kgb_look {
my $cells = shift;
state $points_str = [ map { pp($_) } @points ];
for my $p (@{ $points_str }) {
exists $cells->{$p} or die;
}
exists $cells->{'notfound'} and die;
exists $cells->{'notfound2'} and die;
exists $cells->{'notfound3'} and die;
}
Regards, Mario |