Not related to performance, but rather at ease of use during programming. When I have a subroutine that does something to the values it is passed, I have it run different code paths depending on how the subroutine is called. For example:
sub foo { if (defined wantarray) { # we're in scalar or list context my @param = @_; # make a copy of the parameters foo( @param ); # recursive call for ease of maintenance return @param; # return the result } # we only get here if in void context # do what you need to do on @_ directly, only thing to maintain } #foo
This allows you to use the subroutine in two ways. One directly modifying the parameters passed:
foo( @data );
and one returning the changed parameters, keeping the old:
@newdata = foo( @olddata );
This gives me a lot of flexibility: on the one hand the direct changing which is CPU and memory efficient (no need to copy anything) and the copying way, which also comes in handy if you're passing constant (non left-value) parameters, like so:
@data = foo( qw(foo bar baz) );
If you're really concerned about performance, you could remove the recursive call, but that would leave you with two identical code paths to maintain, which is always a bad thing.

Liz


In reply to Re: Memory Use and/or efficiency passing scalars to subs by liz
in thread Memory Use and/or efficiency passing scalars to subs by knexus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.