Home > Article > Backend Development > What aspects does php code optimization include?
1. Make it as static as possible
If a method can be static, declare it as static, and the speed can be increased by 1/4 . In fact, the main difference in the efficiency of static methods and non-static methods is memory: static methods generate memory when the program starts, and instance methods generate memory while the program is running, so static methods can be called directly, and instance methods must first generate an instance and call it through the instance. Method, static speed is very fast, but too much will occupy memory.
2. Use absolute paths in include and require
If a relative path is included, PHP will traverse the include_path to find the file. Using absolute paths will avoid such problems, so it will take less time to resolve the operating system path.
3. Try to use cache. It is recommended to use memcached
A high-performance distributed memory object cache system to improve the performance of dynamic network applications and reduce the burden on the database; also Caching of OP codes is useful so that scripts do not have to be recompiled for each request.
4. Don’t copy variables casually
Sometimes in order to make the PHP code cleaner, some PHP novices will copy the predefined variables to a shorter name. variables, in fact, the result of this is to double the memory consumption, which will only make the program slower.
5. Use isset instead of strlen in some places
When operating a string and need to check whether its length meets certain requirements, you will naturally use strlen( )function. This function executes quite quickly because it does not do any calculations and just returns the known string length stored in the zval structure (C's built-in data structure used to store PHP variables).
However, since strlen() is a function, it will be somewhat slow, because the function call will go through many steps, such as lowercase letters (Annotation: refers to the lowercase function name, PHP does not distinguish the case of function names ), hash search will be executed together with the called function. In some cases, you can use the isset() trick to speed up the execution of your code.
Recommended tutorial: PHP video tutorial
The above is the detailed content of What aspects does php code optimization include?. For more information, please follow other related articles on the PHP Chinese website!