Reputation: 2282
I am quite new to PHP, and I have a question about IF statements.
Example 1:
<?php
if($a == 1){
if($b == 1){
echo 'test';
}
}
?>
Example 2:
<?php
if($a == 1 && $b ==1){
echo 'test';
}
?>
Both have the same result, but which one is faster? Does it even matter?
Upvotes: 2
Views: 128
Reputation: 95103
This is Premature Optimization & Micro Benchmark , you really need to read Don't be STUPID: GRASP SOLID! to understand why i said so
But if you want to know if($a == 1 && $b ==1)
seems faster is most PHP versions
If you want to know the real difference then look at the opcodes
First Code :
line # * op fetch ext return operands
---------------------------------------------------------------------------------
2 0 > IS_EQUAL ~0 !0, 1
1 > JMPZ ~0, ->7
3 2 > IS_EQUAL ~1 !1, 1
3 > JMPZ ~1, ->6
4 4 > ECHO 'test'
5 5 > JMP ->6
6 6 > > JMP ->7
7 > > RETURN 1
Secound Code
line # * op fetch ext return operands
---------------------------------------------------------------------------------
2 0 > IS_EQUAL ~0 !0, 1
1 > JMPZ_EX ~0 ~0, ->4
2 > IS_EQUAL ~1 !1, 1
3 BOOL ~0 ~1
4 > > JMPZ ~0, ->7
3 5 > ECHO 'test'
4 6 > JMP ->7
7 > > RETURN 1
Can you see how similar with very minimal difference. And that is why it does not make sense to worry about this light this but write good and readable code.
Upvotes: 5
Reputation: 39522
Preoptimization is the root to all evil.
That said, your first piece of code is a tiny bit faster (but again, minimally - don't bother to change your code to this - readability is way more important than the tiny speed incremention you get from changing your conditions.
3,000,000 iterations of the first piece of code: ~ 0.9861679077 seconds
3,000,000 iterations of the second piece of code: ~ 1.0684559345 seconds
Difference: ~ 0.0822880268 seconds
Difference per iteration: ~ 0.0000000274 seconds (or 274 nano seconds).
Upvotes: 1
Reputation: 20286
Both are the same. There are not much code to be optimized you can even write to make shorter syntax.
<?php
echo $a && b ? 'test' : '';
?>
Does the same.
I've modified a bit Baba's benchmark to check the results for shorthand syntax.
Upvotes: 1
Reputation: 1401
Both are same, because PHP interpreter is "smart enough" to figure out that.
Upvotes: 0
Reputation: 31550
No, it does not matter. Such little performance tweaks are usually overcome by the running environment. Such as inefficient algorithms or client side best practices being ignored.
Upvotes: 0
Reputation: 7552
They are the same - in both cases if the first condition is false, the second will not be tested.
Upvotes: 1