Skip to content

Instantly share code, notes, and snippets.

@bessarabov
Created December 23, 2020 19:31
Show Gist options
  • Save bessarabov/9c4c7d996898df044df5b90406f1da08 to your computer and use it in GitHub Desktop.
Save bessarabov/9c4c7d996898df044df5b90406f1da08 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(cmpthese);
my @indexes;
foreach (1..1000) {
my $r = int(rand(10_000));
push @indexes, $r;
}
my @arr;
foreach my $i (@indexes) {
$arr[$i] = $i;
}
my %h;
foreach my $i (@indexes) {
$h{$i} = $i;
}
my $tmp;
cmpthese(
-5,
{
array => sub {
foreach my $i (@indexes) {
$tmp = $arr[$i];
}
},
hash => sub {
foreach my $i (@indexes) {
$tmp = $h{$i};
}
},
},
);
__END__
$ perl perl_benchmark_array_hash_read_2.pl
Rate hash array
hash 10711/s -- -44%
array 18977/s 77% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment