You give 3 examples of concatenating a string:
$var = "foo" ; $var .= "bar" ; # 1 $var = "foo$var" ; # 2 substr($var,0,0) = "foo" ; # 3
Of these ways to do it, I find number 2 the most readable. you can see immediately what is going on. But you claim that method 3 is the fastest, because you don't have to "rewrite" $var.

For fun, I did a little benchmark:

#!/usr/bin/perl -w use Benchmark; timethese(1_500_000, { Interpolate => q/$var = "String"; $var = "foo$var";/, Concatenate => q/$var = "String"; $var = "foo" . $var;/, Substr => q/$var = "String"; substr($var, 0, 0) = 'foo'/ });
On a 1.6GHz P4 machine, I got the following results (Perl 5.8.0):
Benchmark: timing 1500000 iterations of Concatenate, Interpolate, Subs +tr... Concatenate: 1 wallclock secs ( 1.56 usr + 0.00 sys = 1.56 CPU) @ 9 +60000.00/s (n=1500000) Interpolate: 1 wallclock secs ( 1.59 usr + 0.00 sys = 1.59 CPU) @ 9 +45812.81/s (n=1500000) Substr: 2 wallclock secs ( 2.07 usr + 0.01 sys = 2.08 CPU) @ 72 +1804.51/s (n=1500000)
Perl 5.6.1 and 5.005 give similar results; the substr trick is consistently the slowest.

So, optimizations can be very useful, but I doubt that it is in this case. I value readability over performance, within reasonable limits. Most of the time, use of another algorithm can yield far better results than micro-optimizations.

Arjen

Update: I made a little mistake in showing the examples. Now, #1 and #2 are IMO equally readable, depending on what you're doing.


In reply to Re: How Perl Optimize your code & some code TIPS ;-P by Aragorn
in thread How Perl Optimize your code & some code TIPS ;-P by gmpassos

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.