Highly efficient PHP code writing

Summary

To write highly efficient PHP code, prioritize using single quotes for strings and accessing array elements with quoted keys like $row["id"]. Optimize loops by pre-calculating maximum iterations or using foreach, and always unset large unused variables to free memory. Define class methods as static when appropriate, and avoid magic methods like __get, __set, or __autoload. For file inclusion, prefer include with absolute paths over require_once, and utilize built-in functions such as strtr for string manipulation, which is significantly faster than str_replace or preg_replace. Employing switch statements over if/else and closing database connections also contributes to better performance.

Next are some tips for writing highly efficient PHP codes. They are described below:
0. Use single quote to replace double quote, this will be better since PHP will serach for variables in double quoted strings. Note, only echo can do this;
1. If we can define methods of a class as static, then do it. It will increase access speed by 4 times;
2. $row["id"] is 7 times faster than $row[id];
3. echo is faster than print, and also use echo's multiple parameter format such as echo $str1,$str2 instead of echo $str1.$str2;
4. When using for loop, make sure the maximum number of executions instead of calculating maximum execution times in each loop. Use foreach if you can;
5. unset unused variables especially for those large data structures like array to release memory;
6. try best to avoid using __get,__set and __autoload;
7. require_once() cost much;
8. use absolute path when using include() function, it will short the time for searching the included file;
9. If you want to know the execution time of a script, using $_SERVER["REQUEST_TIME"] is better than using time();
10. using functions to replace regular expression to realize the same functions;
11. str_replace() is faster than preg_replace() and strtr is 4 times faster than str_replace();
12. using switch is better than using if else;
13. using @ to hide error message is less efficient;
14. after finish using database connection, close it;
15. using built-in functions whenever you can
PHP TIPS CODE WRITING HIGH EFFICIENT

  RELATED

  COMMENTS

3
Schizoduckie
Mar 6, 2012 at 6:38 am
Stop posting about micro optimisations like this. They are useless, and FUD
jmorton
Mar 6, 2012 at 11:13 pm
@Schizoduckie actually, these sorts of posts are great for novice developers and I have forwarded this article to a handful of up-and-coming php coders I know. Thanks for the post.
Nenad
Nov 9, 2012 at 11:02 pm
Код Ð´Ð»Ñ Ð²ÑтавкиTrackback Hi there! Do you use Twitter? I'd like to follow you if that would be okay. I'm deilnitefy enjoying your blog and look forward to new posts .