Created
April 25, 2017 08:28
-
-
Save yowcow/37571eca15eaf99d8437c32b9422dec1 to your computer and use it in GitHub Desktop.
Hash key access
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use Benchmark qw(cmpthese); | |
sub hv { | |
my ($ref, $key, $default) = @_; | |
defined $ref && exists $ref->{$key} ? $ref->{$key} : $default; | |
} | |
my $hash = { | |
position => 9, | |
}; | |
cmpthese(2_000_000, { | |
'Local var' => sub { | |
if (my $pos = hv($hash, 'position')) { | |
$pos; | |
} | |
}, | |
'Direct hash access' => sub { | |
if (hv($hash, 'position')) { | |
$hash->{position}; | |
} | |
}, | |
'Double hv() call' => sub { | |
if (hv($hash, 'position')) { | |
hv($hash, 'position'); | |
} | |
}, | |
}); | |
=pod | |
Rate Double vh() call Local var Direct hash access | |
Double vh() call 1169591/s -- -46% -55% | |
Local var 2150538/s 84% -- -17% | |
Direct hash access 2597403/s 122% 21% -- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment