Skip to content

Instantly share code, notes, and snippets.

@mpapec
Created May 19, 2016 20:21
Show Gist options
  • Save mpapec/29198302b7cca8d3c74be45ff4b12230 to your computer and use it in GitHub Desktop.
Save mpapec/29198302b7cca8d3c74be45ff4b12230 to your computer and use it in GitHub Desktop.
use 5.20.0;
use strict;
use warnings;
use Benchmark qw(:all);
my $i;
my $fa;
my %hash1;
my %hash2;
my %hash3;
my %hash4;
my %compare = (
uarray => sub {
$fa->(add => $i++);
my $memb = $fa->(members => 1);
for my $v (@$memb) { next if !defined $v; }
},
hash1 => sub {
$hash1{ $i++ } = ();
my @memb = keys %hash1;
for my $v (@memb) {}
},
hash2 => sub {
$hash2{ $i++ } = ();
while (my ($k,undef) = each(%hash2)) {}
},
hash3 => sub {
$hash3{ $i++ } = ();
while (my $k = each(%hash3)) {}
},
hash4 => sub {
$hash4{ $i++ } = ();
while (each(%hash4)) {}
},
);
$i = 0; $fa = uniqArrayFactory(); %hash1 = %hash2 = %hash3 = %hash4 = ();
cmpthese(3000, \%compare);
$i = 0; $fa = uniqArrayFactory(); %hash1 = %hash2 = %hash3 = %hash4 = ();
cmpthese(6000, \%compare);
$i = 0; $fa = uniqArrayFactory(); %hash1 = %hash2 = %hash3 = %hash4 = ();
cmpthese(9000, \%compare);
sub uniqArrayFactory {
my $members = [];
my $seen = {};
my $gaps = [];
return sub {
my (%arg) = @_;
return $members if exists $arg{members};
my $m;
if (defined ($m = $arg{del})) {
return if !$seen->{$m};
${ $seen->{$m} } = undef;
push @$gaps, delete($seen->{$m});
}
elsif (defined ($m = $arg{add})) {
return if $seen->{$m};
if (@$gaps) {
$seen->{$m} = pop @$gaps;
${ $seen->{$m} } = $m;
}
else {
push @$members, $m;
$seen->{$m} = \( $members->[-1] );
}
}
return $m;
};
}
__DATA__
Rate hash2 hash1 hash3 hash4 uarray
hash2 2143/s -- -13% -21% -29% -76%
hash1 2459/s 15% -- -9% -18% -72%
hash3 2703/s 26% 10% -- -10% -69%
hash4 3000/s 40% 22% 11% -- -66%
uarray 8824/s 312% 259% 226% 194% --
Rate hash1 hash2 hash3 hash4 uarray
hash1 1002/s -- -4% -25% -30% -79%
hash2 1047/s 5% -- -21% -27% -78%
hash3 1330/s 33% 27% -- -7% -72%
hash4 1429/s 43% 36% 7% -- -70%
uarray 4800/s 379% 358% 261% 236% --
Rate hash1 hash2 hash3 hash4 uarray
hash1 591/s -- -14% -32% -39% -80%
hash2 685/s 16% -- -22% -29% -77%
hash3 875/s 48% 28% -- -10% -70%
hash4 970/s 64% 41% 11% -- -67%
uarray 2922/s 394% 326% 234% 201% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment