Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Perl and common subexpressions

by Zaxo (Archbishop)
on Dec 23, 2004 at 06:56 UTC ( [id://417011]=note: print w/replies, xml ) Need Help??


in reply to Perl and common subexpressions

Nice to see that quantified, thanks!

A similar optimization can be set up when map or a for loop is applied to the values of a hash or elements of an array,

my $total; $total += $_->{'cost'} for @{$struct[3]{'baz'}[42]};

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Perl and common subexpressions
by Aristotle (Chancellor) on Dec 23, 2004 at 19:44 UTC

    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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://417011]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-19 01:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found