Skip to content

Instantly share code, notes, and snippets.

@mjsr
Created June 20, 2014 10:16
Show Gist options
  • Save mjsr/c056abe24c8d1b3b41e9 to your computer and use it in GitHub Desktop.
Save mjsr/c056abe24c8d1b3b41e9 to your computer and use it in GitHub Desktop.
Benchmark overhead of copying hash reference to a new variable, four times...
#!perl
use warnings;
use strict;
use Benchmark qw( cmpthese );
my $h0 = {
'h1' => {
'h2' => {
'h3' => {
'h4' => {
'key' => 0,
},
},
},
},
};
cmpthese(100_000_000, {
'use_direct' => sub { sub_direct() },
'use_ref' => sub { sub_ref() },
});
sub sub_direct {
$h0->{'h1'}{'h2'}{'h3'}{'h4'}{'key'} = 1;
}
sub sub_ref {
my $h1 = $h0->{'h1'};
my $h2 = $h1->{'h2'};
my $h3 = $h2->{'h3'};
my $h4 = $h3->{'h4'};
$h4->{'key'} = 1;
}
@mjsr
Copy link
Author

mjsr commented Jun 20, 2014

                            Rate    use_ref use_direct
            use_ref    2656042/s         --       -39%
            use_direct 4378284/s        65%         --

Makes sense... Copy ref to the hash into new variable along with the memory allocation for that new variable.
Should make a variant where I have multiple sub_ref like functions that copy less and less references to check if that is linear.

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