Saturday, 14 January 2017

Tips to optimize php script for better performance

1. Use PHP native functions :
         As much as possible try to use native PHP functions rather than writing your own functions to achieve the objective.
2. Use single quotes:
        Using single quotes is faster than using double quotes. If you are going to keep only the string inside it avoiding any variables.
3. Use === :
        Use '===' inserted of '==' as the former strictly checks for a closed range which makes it faster.
4. Use appropriate str function :
        str_replace is faster than preg_replace but strstr is faster than str_replace.
5. Calculate only once :
        calculate and assign the value to the variable it that value is getting used numerous time rather than calculating it again and again where it is being used.
eg. for($i=0;$i<count($array); $i++)
better
$len=count($array);
for($i=0;i<$len;$i++)
6. Pass reference to function :
        pass reference to the function if it is not affected your logic.A function manipulation the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created.
7. Created classes when it's required :
        Don't create classes and methods until and unless its really needed. used and reused as well.
8. Disable debugging messages :
        File operations are expensive so if you have written lot of custom functions to log errors and warning during your development process make sure you remove them before you push the code to production.
9. Use caching techniques :
        use cache to reduce the load of database operations as well as the script compilation. mem cache for reducing database load and APC for opcode caching and intermediate code optimization.
10. Close the connection :
           Get into the habit to unset the variables and close database connection in your PHP code it save memory.
11. Reduce number of hits to database:
           Try to reduce the number of hits to the database. make queries aggregate so that you call the database less number of times.
12. Frequently used switch cases :
           Keep most frequently used switch case on the top.
13. Use method in derived classes:
            Method in derive class is faster than base class.
14. Use JSON :
          use JSON insated of XML while working with web services as therer are native PHP function like json_encode() and json_decode() which are very fast.
15. Use isset :
          Use isset where every possible insted of using count(), strlen(),sizeof() to check out greater then 0.

2 comments: