Beefy Boxes and Bandwidth Generously Provided by pair Networks httptech
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Temp variable performace vs Inline behavior

by muba (Priest)
on Jun 27, 2012 at 15:10 UTC ( #978690=note: print w/ replies, xml ) Need Help??


in reply to Temp variable performace vs Inline behavior

I'd go for the first version, with the temporary variable, for the exact reason you mention: the second version has an extra call to the subroutine. The extra memory overhead shouldn't be much of a problem. I don't think you're dealing with gigabites of data here at once.

Another reason the first version is preferable because the call to the subroutine in the if clause may have side effects that will affect the value that will be pushed onto the array. The following script demonstrates what I mean.

Update: there was a stupid little error in the script. Fixed.

use strict; use warnings; use subs qw( version1 version2 ); my @delete = qw(bar baz); my %hash = (foo => 1, bar => 2, baz => 3); print "Keys in the hash: ", join(", ", keys %hash), "\n"; print "Version 1 reports ", version1, " as the sum of values deleted f +rom the hash.\n"; print "Keys in the hash after version 1: ", join(", ", keys %hash), "\ +n"; print "\n"; %hash = (foo => 1, bar => 2, baz => 3); print "Keys in the hash: ", join(", ", keys %hash), "\n"; print "Version 2 reports ", version2, " as the sum of values deleted f +rom the hash.\n"; print "Keys in the hash after version 2: ", join(", ", keys %hash), "\ +n"; sub version1 { my $num_deleted = 0; for (@delete) { my $deleted = delete $hash{$_}; $num_deleted += $deleted if $deleted; } return $num_deleted } sub version2 { my $num_deleted = 0; for (@delete) { $num_deleted += delete $hash{$_} if delete $hash{$_} } return $num_deleted } __END__ Keys in the hash: bar, baz, foo Version 1 reports 5 as the sum of values deleted from the has. Keys in the hash after version 1: foo Keys in the hash: bar, baz, foo Use of uninitialized value in addition (+) at G:\y.pl line 35. Use of uninitialized value in addition (+) at G:\y.pl line 35. Version 2 reports 0 as the sum of values deleted from the hash. Keys in the hash after version 2: foo


Comment on Re: Temp variable performace vs Inline behavior
Download Code
Re^2: Temp variable performace vs Inline behavior
by Ransom (Beadle) on Jun 27, 2012 at 15:18 UTC
    Didn't even think about side effects!

    Thanks for the example and snippet. It's good to know that parse_node does indeed get called twice.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (13)
As of 2014-04-18 17:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (471 votes), past polls