in reply to How Perl Optimize your code & some code TIPS ;-P

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-

Replies are listed 'Best First'.
Re^2: How Perl Optimize your code & some code TIPS ;-P
by Aristotle (Chancellor) on Jan 24, 2003 at 17:10 UTC
    An extremly good but often forgotten point. On this topic, it should be pointed out that any results will vary wildly depending on input data in nearly every case. In order to benchmark meaningfully then, you have to be very careful about the characteristics of your sample set - subtle properties you may not even be aware of could easily cause significant variation.

    Makeshifts last the longest.