Perfect. This is what I was expecting to see. Yes, non-lvalue functions copy their result.

$ perl -MDevel::Peek -e'Dump sub { my $x = "abc"; Dump $x; $x }->()' SV = PV(0x8bfe730) at 0x8c1b2b0 REFCNT = 1 FLAGS = (PADMY,POK,pPOK) PV = 0x8c16088 "abc"\0 <-- Note the address CUR = 3 LEN = 12 SV = PV(0x8bfe780) at 0x8c00768 REFCNT = 1 FLAGS = (TEMP,POK,pPOK) PV = 0x8c1e2e0 "abc"\0 <-- A copy CUR = 3 LEN = 12

That's why returning a string ($ref = \out1()) is as expensive as assigning a string ($str = ${ out2() }).

So why is both returning a string and assigning it not ($str = out1()) twice as expensive?

When assigning a string slated to be destroyed* such as the automatic copy of a return value, the assignment will steal the buffer instead of copying it.

* — (FLAGS & TEMP) && REFCNT == 1, I think.


In reply to Re^3: How to avoid string copies in function calls? by ikegami
in thread How to avoid string copies in function calls? by Anonymous Monk

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.