The difference is so insignificant that it is actually far more important whether the condition being evaluated has an affirmitive outcome (meaning the return 1 gets executed) or not.
Consider the following code:
use strict;
use warnings;
use Benchmark qw/cmpthese/;
cmpthese( -1, {
Std_pos => sub { my $n = 0; if( $n < 1 ) { return 1 } },
# Std_neg => sub { my $n = 1; if( $n < 1 ) { return 1 } },
Rflx_pos => sub { my $n = 0; return 1 if $n < 1; },
# Rflx_neg => sub { my $n = 1; return 1 if $n < 1; },
And_pos => sub { my $n = 0; $n < 1 and return 1; },
# And_neg => sub { my $n = 1; $n < 1 and return 1; },
} );
...and the results...
Rate And_pos Std_pos Rflx_pos
And_pos 4338935/s -- -4% -5%
Std_pos 4504851/s 4% -- -2%
Rflx_pos 4574559/s 5% 2% --
Note, in the preceeding code, we're only comparing the cases where the conditional evaluates to true, so the 'return 1' is executed. Notice how the fastest method (reflexive, I call it) is only 5% faster than "and", and only 1% faster than "Standard".
When you compare only the code where all conditionals evaluate to false (ie, return 1 is not executed), you get the following results, which are slightly more interesting, but not enough so to get worked up over:
Rate And_neg Rflx_neg Std_neg
And_neg 5286632/s -- -2% -14%
Rflx_neg 5401907/s 2% -- -12%
Std_neg 6149593/s 16% 14% --
But now uncomment the negs and the pos's, and see how the comparison turns out when you compare the code that evaluates to true versus the code that evaluates to false:
Rate Std_pos Rflx_pos And_pos Rflx_neg And_neg Std_n
+eg
Std_pos 4254827/s -- -3% -3% -15% -21% -2
+2%
Rflx_pos 4368927/s 3% -- -0% -13% -19% -2
+0%
And_pos 4376827/s 3% 0% -- -13% -19% -2
+0%
Rflx_neg 5023657/s 18% 15% 15% -- -7% -
+8%
And_neg 5386758/s 27% 23% 23% 7% -- -
+2%
Std_neg 5486976/s 29% 26% 25% 9% 2%
+--
Notice how all the negatives are grouped together, as the fastest (because they don't execute the 'return 1'). ...and they're 18% to 29% faster than their corresponding 'positives'. In other words, the return 1 is much more significant than the syntax chosen to control the flow.
Perhaps the most important thing to notice is that, when comparing all together, the best case executes almost five and a half million times a second, and the worst case over four and a quarter million times a second. To me that says I'm probably looking in the wrong place to optimize. You should really just profile and see if this is where your issue is, and also examine your algorithms to see if they're well thought-out.
Focus on profiling, and the algorithms at work, and forget about such insignificant syntax differences. If you have to care whether it's faster to use if( ... ) {...} or ... if ..., you may have to polish up your assembler skills anyway.
|