10 PHP Optimisation Techniques
Sunday, January 20th, 2008Many people write php code without knowing how to optimise it properly to make it run faster. By applying some simple coding techniques your php script can run faster and save cpu workload. Also if your script is large then pages will load faster if the script is optimised.
1. Arrays are slower than normal variables. The speed difference is significant. Obviously only applicable to when you use small arrays. I calculated the array to take about twice as long.
2. Arrays are faster than objects. This is again a significant speed difference. Decide whether is is worth having objects in all cases. Consider using an array instead. The objects took about twice as long.
3. Functions outside of objects are slower than functions inside of objects. The function within the object takes roughly 50% longer.
4. Local variable inside a function are fractionally faster than global variables. Consider setting local variables to the value of the global variable if it is going to be used in a loop. The global took roughly 15% longer.
5. Multiplication is slightly faster than division. So it is better to multiply by 0.5 than divide by two. Consider pre calculating a division outside of a loop by storing 1/value and then multiplying with the new value. the division took about 10% longer.
6. Multiplication is a lot faster than the pow() function. Use $x * $x rather than pow($x, 2). the pow() function took roughly four times as long.
7. Receiving the return value from a function is slower than if you do not receive it. When your script is complete then the error checking by looking at the return from a function may not be necessary. Setting the variable took roughly 18% longer.
8. Using a loop is faster than using a recursive function. See if it is possible to code with a loop.
9. echo() is faster than print(). This is due to generally unnecessary error checking in print().
10. Single quotes are faster than double quotes. This is because with double quotes the text inside the quotes is checked for variables and other things. There are times to use each one but I will not go into it in depth here. Basically use single quotes when the text is completely static.
11. (Contributed by InSp3KtaH) You should not change the type of a variable. It you set $foo = 1 then you should keep it as a number. It takes time and memory to change the type.
You may have noticed that some of these techniques could come into conflict with keeping well written object orientated code. In each case you have to consider the pros and cons. There are no fixed rules so you will have to decide whether to sacrifice feed for code clarity. If large loops are to be found in your code look at optimising these very carefully as that is where a lot of performance goes.
