Skip to content

Instantly share code, notes, and snippets.

@karupanerura
Created August 20, 2011 01:52
Show Gist options
  • Save karupanerura/1158487 to your computer and use it in GitHub Desktop.
Save karupanerura/1158487 to your computer and use it in GitHub Desktop.
can vs hash table
package Tokyo;
package Chiba;
package main;
use strict;
use warnings;
use Benchmark qw/cmpthese timethese/;
my $table = +{
Tokyo => +{
shinagawa => 1,
tokyo => 1,
asakusa => 1,
akihabara => 1,
sinjyuku => 1,
shibuya => 1,
},
Chiba => +{
chiba => 1,
narita => 1,
hunabashi => 1,
kisarazu => 1,
matsudo => 1,
},
};
my @package_list;
my @key_list;
foreach my $big_key (keys %$table) {
push(@package_list, $big_key);
foreach my $key ( keys %{ $table->{$big_key} } ) {
push(@key_list, $key);
no strict 'refs';
*{"${big_key}::$key"} = sub { 1 };
}
}
cmpthese timethese(1000000, +{
table => sub {
foreach my $pkg (@package_list) {
foreach my $key (@key_list) {
exists($table->{$pkg}) && exists($table->{$pkg}{$key});
}
}
},
can => sub {
foreach my $pkg (@package_list) {
foreach my $key (@key_list) {
$pkg->can($key);
}
}
},
});
__END__
$ perl benchmark.pl [branch:master]
Benchmark: timing 1000000 iterations of can, table...
can: 10 wallclock secs ( 9.97 usr + 0.00 sys = 9.97 CPU) @ 100300.90/s (n=1000000)
table: 7 wallclock secs ( 6.44 usr + 0.00 sys = 6.44 CPU) @ 155279.50/s (n=1000000)
Rate can table
can 100301/s -- -35%
table 155280/s 55% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment