Your tests are bad. The only copying is happening outside of the functions you are testing. Specifically, they occurring when you assign the string to $tmp in $tmp = out1() and in $tmp = fun1($str).

Right now, you have

my $str = out1(); my $ref = out2(); my $str = fun1($str); my $ref = fun2(\$str);

If you wanted to fix the test, you'd use

my $str = out1(); my $str = ${ out2() }; my $str = fun1($str); my $str = ${ fun2(\$str) };

or

my $ref = \out1(); my $ref = out2(); my $ref = \fun1($str); my $ref = fun2(\$str);

As you can see, passing a string by reference seems to slow down (in2 is slower than in1)

Perl always passes by reference. in2 passes *a* reference (by reference). This reference has to be created, dereferenced and destroyed. This is all work that in2 does on top of what in1 does, so of course it will be slower.

Update: The last paragraph was saying "out1" and "out2" when I meant "in1" and "in2". Fixed.


In reply to Re: 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.