This post covers some performance improvement tips by showing merits or demerits of various coding practices in PHP. While developing small websites or projects which are not meant to be maintained for longer period of time it's okey it we don't care about all this performance improvement and so on. But while we are into the development of some product or project which are going to be maintained for longer period of time then it is required that we take care of small things from the beginning. Initially we may feel that benefits are not drastic but when we have large amount of user base then all small and minor things matters.
In PHP we have always so many ways to do things. During development of PHP as a language, developer community/team added up many functions and features (due to requests..!) in the language and some of them might be redundant, so we have sometimes many ways to solve one problem. Here sometimes due to not knowing what is the best way to solve the problem, we use the solution which we already know or we are more familiar with. Sometimes as a developer we create habit of doing something in particular way for always. Please read on to know whether you are already aware of this tips, which could improve performance of your php application. (Even if it is micro improvement it matters..!)
- Don't use foreach loop as long as you can avoid it, for loops are faster than any other looping constructs.
When it comes to various looping constructs and control statements it could differ based on case to case. Please refer http://www.phpbench.com/ by Chris Vincent, he has done remarkable job by providing detailed benchmarks with various combinations. - echo is faster than print. As echo is one of the language construct which don't return anything while print will return 0 or 1 based on success or failure.
- include_once is costlier then include statement. As it will have to look whether class definition you are trying to include is already included or not?
- Always use single quotes for long strings and not the double quotes. Because for double quotes php will try to search and evaluate $vars found in that string.
So in that case echo 'It was really a long story to finish '. $name is faster then echo "It was really a long story to finish $name".
But then echo 'It was really a long story to finish' , $name can be faster then first one too, as it don't required any string manipulation from php and just outputting all arguments to screen. This matters most when we need to do lots of text processing or html to be generate from our application/scripts. - Magic methods like __string,__set,__get can slow down things. But it's okey as it can give more clarity in our code. Personally I like to use __set and __get as it let me stay away from getter and setter methods. __autoload is expensive and if you don't really need it then don't use them.
- Don't use for($i=0; $i<=count($arrPerson); $i++) {..} instead use,
for($i=0,$total = count($arrPerson); $i<$total; $i++) {..}. The previous one will call count function for each iteration of the loop while the second one will call count function just once. - If you can declare a method as static then let it be static, they are faster around 33% then member functions.
- $arrPerson[‘name'] is faster than $arrPerson[name]. So try using single quotes for associative arrays.
- If you can solve your any problem without using regular expressions, then don't use them. Regex functions are slower than their php counterparts. For example use str_replace instead of preg_replace if it can do serve your purpose.
- If you will provide array as any argument for str_replace it will be faster instead of giving string inputs for single search and replacement.
Slow:
str_replace( ‘search', ‘replace',$strAssay);
Fast:
str_replace(array(‘search'),array(‘replace'),$strAssay); - Try to minimize the relative paths for file include. For relative path includes it will search into default include path then current directory and so on.. So file search in that case can take long time. Instead specify WEB_ROOT constant which will be physical path of your web directory and which could be defined by following way.
define('WEB_ROOT',str_replace(array('\\'),array('/'),dirname(__FILE__)) . '/'); - Identical operator (===) is faster than (==) operator as identical operator will include type checking also. So If( 1 == '1') will return true, If( 0 == '') will return true while if you use identical operator both this conditions If( 1 === '1') and If(0 === '') will return false. So it is recommended to use identical operator when you are going to use some boolean variables for deciding the flow/control of your application.
- Don't use short tags <? and try using <?php, it can heart you when you go an deploy your application on some other servers.
- Don't use or relay on register_globals or magic quotes and read and configure your php.ini settings carefully. You can read comments over parameters and can set those parameters based on your server setup and application requirement for optimum performance.
- Disable or comment extensions you are not going to use ever from php.ini
In addition to all this develop or follow coding standard for variables, classes, methods and file naming. It will reduce development time due to certainty. Always use proper variable names there is nothing wrong having variable name like $blnIsVARAdminLoggedIn. Proper naming convention will help you and your team members while it comes to maintenance part of the project. Writing comments for not understandable variable or method names would be less helpful. Use editors with auto-complete feature like Eclipse, Aptana which would reduce the hard-work for typing long variable or method names.
Related Material: PHP Coding Standard by Fredrik Kristiansen / DB Medialab
Please have your comments on this post and add-up anything which could help us improve as a PHP Professional.
#1 by BruceT on August 10, 2008 - 5:31 am
Quote
In #6, isn’t the $total variable setting still inside the loop with your syntax?
for($i=0,$total = count($arrPerson); $i<$total; $i++) {..}
I would do it as:
$total = count( $arrPerson );
for ( $i = 0; $i < $total; $i++ ) {..}
to make it much clearer what I was doing. That comma might be overlooked, etc.
#2 by Dharmavirsinh Jhala on August 10, 2008 - 11:31 am
Quote
Hi Bruce,
That’s true that $total could be overlooked in my case, but then if you are declaring outside for loop then it will exist in the program during the execution of the script.
So if we are going to utilize that $total somewhere else in our script then better we declare outside else if we intend to use only inside for loop then it could be declared like below..
for($i=0,$total = count($arrPerson); $i<$total; $i++) {..}
#3 by Addy on August 10, 2008 - 12:56 pm
Quote
These tips are absurd. The most time this stuff will save you is a couple of milliseconds. Instead of trying to give people a “quick fix” to increase their speed, you should teach them good programming habits which will actually save them time.
#4 by Sausage on August 10, 2008 - 1:13 pm
Quote
“Don’t use foreach loop as long as you can avoid it, for loops are faster then any other looping constructs.”
Definately true in PHP 4, but I haven’t seen one case where it’s faster in 5.
#5 by Dharmavirsinh Jhala on August 10, 2008 - 4:43 pm
Quote
Hi Addy,
As you told this tips will save milliseconds and our script won’t take minutes to execute.
Making habit and knowing that what will save your few milliseconds will make one good programmer.
#6 by Dharmavirsinh Jhala on August 10, 2008 - 5:03 pm
Quote
Hi Sausage,
I have updated my blog and please refer http://www.phpbench.com/ for complete benchmarks on looping and control statements.
Pingback: Turulcsirip - Dobi Attila
#7 by Jaik on August 11, 2008 - 1:12 pm
Quote
Regarding point 4, using double quotes was in fact just as fast as single quotes in my benchmarks when concatenating variables. So this:
echo “My name is ” . $name;
was just as fast as this:
echo ‘My name is ‘ . $name;
#8 by Dominik on August 11, 2008 - 7:35 pm
Quote
I have to agree with Addy: Even though you should try to make use of this knowledge when you write new apps, this is not what you have to look for when your app is running slow. Your app will not suddenly run twice as fast when you replace all ” with ‘…
What’s really slowing down web apps is stuff that’s going on on your servers’ harddrives, i.e. database access (you’ve got to know where you need indexes or where you can precalculate anything) and loading tons of include files.
#9 by Laars Johnsen on August 11, 2008 - 11:19 pm
Quote
Spelling matters. Proofreading will increase your credibility.
Pingback: [ kurt-network ] » Links
Trackback: Added by a Pal to FAQPAl
Pingback: CreatingDrew Weekly-Issue 1 | CreatingDrew
Pingback: Vance Lucas » Premature Performance Benchmarking is a Disease
Pingback: Writing better (performing) code..! What is that? : Blog Archive : blogs@DiGiTSS
Pingback: PHP : Performance Improvement Tips | Jaric's Blog