Just a caveat to your tip on the order of tests in conditional statements.

While what you say is true for an if that is executed only once, things get a bit more subtle if the conditional statement is part of the body of a loop.

In that case, the most expensive test is not so obvious to determine, since it could be the case that a cheaper one almost always succeeds so that the more expensive one is called almost all the time anyway, hence slowing execution since the cheaper test wasn't the determining factor but got executed anyway.

In such a situation only careful benchmarking will yield the correct order since that is a balance between the number of times the tests fail/succeed and the amount of time they take to compuate.

The same holds true for tests in iterations such as the while () and the for ().

By way of example, consider the following loop:

foreach my $file (@dir) { if ($file eq '.' || $file eq '..' || $file =~ /\.bak$/) { ... } }
Obviously the first two tests are cheaper than the last one, but on the other hand, they'll each only succeed once, while the last test may succeed many time. Or, conversely, the last test will be executed very often, regardless of the first two tests.

Just my 2 cents, -gjb-


In reply to Re: How Perl Optimize your code & some code TIPS ;-P by gjb
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.