Interestingly, doing that for the simple case seems to actually impede rather than help performance:
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw( cmpthese );
my @bogus;
$bogus[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ baz } = 5;
$bogus[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ quux } = 6;
our @bogus2;
$bogus2[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ baz } = 5;
$bogus2[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ quux } = 6;
cmpthese( -3 => {
without_common => sub {
my $prod = $bogus[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ baz } *
$bogus[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ quux };
},
with_common => sub {
my $common = $bogus[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ];
my $prod = $common->{ baz } * $common->{ quux };
},
with_for => sub {
my $prod;
$prod = $_->{ baz } * $_->{ quux } for $bogus[ 1 ]{ foo }[ 2 ]
+{ bar }[ 3 ];
},
with_for_g => sub {
my $prod;
$prod = $_->{ baz } * $_->{ quux } for $bogus2[ 1 ]{ foo }[ 2
+]{ bar }[ 3 ];
},
without_common_g => sub {
my $prod = $bogus2[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ baz } *
$bogus2[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ]{ quux };
},
with_common_g => sub {
my $common = $bogus2[ 1 ]{ foo }[ 2 ]{ bar }[ 3 ];
my $prod = $common->{ baz } * $common->{ quux };
},
} );
__END__
Rate with_for with_for_g without_common without_c
+ommon_g with_common with_common_g
with_for 346092/s -- -1% -17%
+ -19% -36% -37%
with_for_g 350487/s 1% -- -16%
+ -18% -35% -37%
without_common 416843/s 20% 19% --
+ -3% -23% -25%
without_common_g 429491/s 24% 23% 3%
+ -- -20% -22%
with_common 537863/s 55% 53% 29%
+ 25% -- -3%
with_common_g 553408/s 60% 58% 33%
+ 29% 3% --
I have to say this result surprised me.
Makeshifts last the longest. |