Skip to content

Instantly share code, notes, and snippets.

@bessarabov
Created December 23, 2020 19:30
Show Gist options
  • Save bessarabov/4f6f7fd23cf447941072dad3165498aa to your computer and use it in GitHub Desktop.
Save bessarabov/4f6f7fd23cf447941072dad3165498aa 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;
}
cmpthese(
-5,
{
array => sub {
my @arr;
foreach my $i (@indexes) {
$arr[$i] = $i;
}
},
hash => sub {
my %h;
foreach my $i (@indexes) {
$h{$i} = $i;
}
},
},
);
__END__
$ perl perl_benchmark_array_hash_write_2.pl
Rate hash array
hash 2165/s -- -81%
array 11697/s 440% --
@jef-sure
Copy link

#!/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;
my %h;

cmpthese(
-5, {
array => sub {
@arr = ();

        foreach my $i (@indexes) {

            $arr[$i] = $i;
        }
    },
    hash => sub {
        %h = ();

        foreach my $i (@indexes) {
            $h{$i} = $i;
        }
    },
},

);
END
Rate hash array
hash 6761/s -- -65%
array 19247/s 185% --

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment