Monday, 13 July 2015

PHP: TIPS FOR OPTIMIZING PHP CODE

1. If a method can be static, declare it static, speed can be improved.

2. Echo is more faster than print.

3. Use Echo’s multiple parameters instead of string concatenation.

4. Unset your variables to free memory, especially large arrays.

5. Avoid magic like __get, __set, __autoload.

6. Require_once() is expensive.

7. Use full paths in includes and requires, less time spent on resolving the OS paths.

8. str_replace is faster than preg_replace, but strtr is faster than str_replace

9. Error suppression with @ is very slow.

10. Close your database connections when you’re done with them

11. Error messages are expensive

12. Incrementing a global variable is 2 times slower than a local var.

13. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

14. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

15. Use any frame works (For example cake php,yii frame work)

16. Use Ternary Operators in your coding

17. Methods in derived classes run faster than ones defined in the base class.

18. Use if else conditions are more faster than the select statements.

19.Avoid looping in your coding.When you use array go for the foreach loop rather than for loop.

20. Don’t use short tags in your coding.

21. ++$i is more faster than $ i++ ,use pre-increment when it is possible.

22. Avoid the PHP mail() function header injection issue.

23. $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.

24. Separate code, content and presentation: keep your PHP code separate from your HTML.

25. Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5, hash.

26. Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory.

2 comments: