Which construction is faster:
$a = $b * $c ? $b * $c : 0;
or
$i = $b * $c;
$a = $i ? $i : 0;
All variables are local ones.
Does speed differs for mulitplication, addition, substraction and division?
Update:
Here’s some clarification:
- This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".
- I can measure code speed by myself. But it’s was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).
- Moreover – I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.
BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!
If you have PHP 5.3, this is faster:
This is the same as
$a = $b * $c ? $b * $c : 0;, but the$a*$bcalcultation is done only once. Also, it doesn’t do additional assignments as in your second solution.Using Martin v. Löwis’s benchmark script I get the following times:
Now these are micro-optimizations, so there is probably many ways of optimizing your code before doing this 🙂
If it is not the case, you may also want to compare generated PHP OP codes:
1
$a = $b * $c ? $b * $c : 0;:2
$i = $b * $c; $a = $i ? $i : 0;3
$a = $b * $c ?: 0;:These OP code listings was generated by the VLD extension.