These tips collected by the author come from a wide range of sources and the completeness cannot be guaranteed. Due to the large number, these optimization techniques were not tested. Please test it yourself before using it. After all, whether these techniques can come in handy depends on the unique environment in which PHP is located.
Directory Index
Finding the Bottleneck
When facing a performance problem, the first step is always to find the cause of the problem, rather than looking at a list of tips. Understand the cause of the bottleneck, find the target and implement the fix, then test again. Finding bottlenecks is only the first step in a long journey of thousands of miles. Here are some common tips. I hope it will be helpful to find the bottlenecks in the most important first step.
- Use monitoring methods (such as monitoring treasure) to conduct benchmarking and monitoring. Networks, especially network conditions, change rapidly. If done well, bottlenecks can be found in 5 minutes.
- Dissect the code. You must understand which parts of the code take the most time and pay more attention to these places.
- To find bottlenecks, check each resource request (for example, network, CPU, memory, shared memory, file system, process management, network connection, etc...)
- First benchmark the iteration structure and complex code
- Conduct real testing with real data under real load. Of course, it is best to use a production server if possible.
Caching
Some people think caching is one of the most effective ways to solve performance problems, try these:
- Use OPCODE cache so scripts are not recompiled on every access. For example: enable the windows cache extension on the Windows platform. Can cache opcodes, files, relative paths, session data and user data.
- Consider using distributed cache in a multi-server environment
- Call imap_headers() before calling imap_header()
Compiling vs. Interpreting
Compile PHP source code into machine code. Dynamic interpretation performs the same compilation, but it is performed line by line. Compiling to opcode is a compromise. It can translate the PHP source code into opcode, and then convert the opcode into machine code. The following are related tips on compilation and interpretation:
- Compile PHP code into machine code before going online. Although opcode caching is not the best choice, it is still better than interpreted. Alternatively, consider compiling the PHP code into a C extension.
- PHP’s opcode compiler (bcompiler) is not yet available for use in production environments, but developers should pay attention to http://php.net/manual/en/book.bcompiler.php.
Code weight loss (Content Reduction)
The less, the chunkier. These tips can help reduce code:
- Fewer features per page
- Clean web content
- If executing interpreted, please clean up comments and other whitespace
- Reduce database queries
Multithreading & Multiprocessing
From fastest to slowest:
PHP does not support multi-threading, but multi-threaded PHP extensions can be written in C. There are some ways to use multiple processes or simulate multiple processes, but the support is not very good and may be slower than a single process.
Strings
String processing is one of the most commonly used operations in most programming languages. Here are some tips to help us make string processing faster:
- PHP’s connection operation (point operation) is the fastest linking method
- Avoid concatenating strings in print, separate them with commas and use ECHO
- Use str_ prefixed string functions instead of regular expressions whenever possible
- pos() is faster than preg_mach() and ereg()
- Some people say that wrapping a string in single quotes is faster than double quotes, while others say there is no difference. Of course, if you want to quote a variable in a string, single quotes are useless.
- If you want to determine whether the string length is less than a certain value (such as 5), please use isset($s[4])<5.
- If you need to concatenate multiple small strings into one large string, try to enable the ob_start output cache first, then use echo to output to the buffer, and then use ob_get_contents to read the string
Regular Expressions
Regular expressions bring us flexible and diverse methods of comparing and searching strings, but their performance overhead is not low
- Use STR_ prefixed string processing functions instead of regular expressions whenever possible
- The use of [aeiou] is not (a|e|i|o|u)
- The simpler the regular expression, the faster it is
- Do not set the PCRE_DOTALL modifier if possible
- Use ^.* instead of .*
- Simplify regular expressions. (For example, use a* instead of (a+)*
Iteration Constructs (for, while))
Iteration (repetition, loop) is the most basic structured programming method. It is difficult to imagine a program that does not use it. Here are some tips to help us improve the performance of iterative structures:
- Move code out of the loop as much as possible (function calls, SQL queries, etc...)
- Use i=maxval;while(i–) instead of for(i=0;i
- Use foreach to iterate over collections and arrays
Selection Constructs (if, switch)
Same as the iterative structure, the selection structure is also the most basic structural transformation method. The following tips may improve performance:
- Among switches and else-ifs, the ones that often appear true recently should be listed first, and the ones that rarely appear true should be listed at the back
- Some people say if-else is faster than switch/case. Of course, some people object.
- Use elseif instead of else if.
Functions & Parameters
Breaking the code of a function into small function code can eliminate redundancy and make the code readable, but at what cost? Here are some tips to help you use functions better:
- Pass objects and arrays by reference instead of by value
- If used in only one place, use inline. If called in multiple places, consider inlining, but please be aware of maintainability
- Understand the complexity of the functions you use. For example, similar_text() is O(N^3), which means that if the string length is doubled, the processing time will be increased by 8 times
- Don't improve performance by "returning references", the engine will automatically optimize it.
- Call the function in the regular way instead of using call_user_func_array() or eval()
Object-Oriented Constructs
PHP’s object-oriented features may affect performance. The following tips can help us minimize this impact:
- Not everything needs to be object-oriented, and the loss of performance may outweigh the advantages itself
- Creating objects is slow
- If possible, use arrays instead of objects whenever possible
- If a method can be made static, please declare it statically
- Function calls are faster than derived class method calls, and derived class method calls are faster than base class calls
- Consider copying the most commonly used code in the base class into the derived class, but be aware of maintenance hazards
- Avoid using native getters and setters. If you don't need them, delete them and make the properties public
- When creating complex PHP classes, consider using the singleton pattern
Session Handling
Creating sessions has many benefits, but sometimes it incurs unnecessary performance overhead. The following tips can help us minimize performance overhead:
- Don’t use auto_start
- Do not enable use_trans_sid
- Set session_cache_limited to private_no_expire
- Assign each user in the virtual host (vhost) its own directory
- Use memory-based session processing instead of file-based session processing
Type Casting
Converting from one type to another has a cost
Compression
Compress text and data before transmission:
- Use ob_start() at the beginning of the code
- Use ob_gzhandler() to speed up downloading, but pay attention to CPU overhead
- Apache’s mod_gzip module can compress instantly
Error Handling
Error handling affects performance. What we can do is:
- Record error logs, do not use "@" to suppress error reports, suppression will also have an impact on performance
- Don’t just check the error log, the warning log also needs to be processed
Declarations, Definitions, & Scope
Creating a variable, array or object has an impact on performance:
- Some people say that declaring and using global variables/objects is faster than local variables/objects, but some people object. Please test before deciding.
- Declare all variables before using them, do not declare unused variables
- Use $a[] in loops whenever possible and avoid using $a=array(…)
Memory Leaks
This is definitely a problem if memory is allocated and not released:
- Insist on releasing resources and don’t expect built-in/automatic garbage collection
- Try to unset variables after use, especially resource classes and large array types
- Close the database connection after use
- Every time you use ob_start(), remember ob_end_flush() or ob_end_clean()
Don’t Reinvent the Wheel
Why spend time solving problems that others have already solved?
- Learn about PHP, its features and extensions. If you don’t know, you may not be able to take advantage of some of the existing features
- Use the built-in array and string functions, they are definitely the best performers.
- The wheel invented by predecessors does not mean that it is the best to absorb energy in your environment. Test more
Code Optimization
- Use an opcode optimizer
- If it will be interpreted and run, please simplify the source code
Using RAM Instead of DASD
RAM is much faster than disk. Using RAM can improve some performance:
- Move files to Ramdisk
- Use memory-based session processing instead of file-based session processing
Using Services (e.g., SQL)
SQL is often used to access relational databases, but our PHP code can access many different services. Here are some things to keep in mind when accessing services:
- Don’t ask the server about Dongfang over and over again. Use memoization to cache the first result, and future visits will go directly to the cache;
- In SQL, use mysql_fetch_assoc() instead of mysql_fetch_array() to reduce the integer index in the result set. Access the result set by field name, not index number.
- For Oracle database, if there is not enough available memory, increase oci8.default_prefetch. Set oci8.statement_cache_size to the number of statements in your application
- Please use mysqli_fetch_array() instead of mysqli_fetch_all() unless the result set will be sent to other layers for processing.
Installation & Configuration
When installing and configuring PHP, please consider performance:
- Add more memory
- Remove competing apps and services
- Only compile the extensions you need
- Static compile PHP into APACHE
- Use -O3 CFLAGS to enable all compiler optimizations
- Only install the modules you need
- Upgrade to the latest minor version. When upgrading the motherboard, wait until the first bug is fixed. Of course, don’t wait too long
- Configure for multi-CPU environments
- Use -enable-inline-optimization
- Set session.save_handler=mm, compile with -with-mmto, use shared memory
- Use RAM disk
- Close resister_global and magic_quotes_*
- Close expose_php
- Turn off always_populate_raw_post_data unless you must use it
- Please turn off register_argc_argv in non-command line mode
- Only use PHP in .php files
- Optimize the parameters of max_execution_time, max_input_time, memory_limit and output_buffering
- Set allowoverride in the Apache configuration file to none to improve file/directory access speed
- Use -march, -mcpu, -msse, -mmmx, and -mfpmath=sseto to optimize the CPU
- Use MySQL native driver (mysqlnd) to replace libmysql, mysqli extension and PDO MYSQL driver
- Close register_globals, register_long_arrays and register_argc_argv. Enable auto_globals_jit.
Other
There are also some skills that are harder to classify:
- Use include(), require(), avoid include_once() and require_once()
- Use absolute paths in include()/require()
- Static HTML is faster than HTML generated by PHP
- Use ctype_alnum, ctype_alpha and ctype_digit instead of regular expressions
- Use simple servlets or CGI
- When the code is used in a production environment, write logs as much as possible
- Use output buffering
- Please use isset($a) instead of comparing $a==null; please use $a===null instead of is_nul($a)
- If you need the script start execution time, please read $_SERVER[’REQUEST_TIME’] directly instead of using time()
- Use echo instead of print
- Use pre-increment (++i) instead of post-increment (i++). Most compilers will now optimize, but when they don't, please keep writing like this.
- Process XML, use regular expressions instead of DOM or SAX
- HASH algorithm: md4, md5, crc32, crc32b, sha1 are faster than other hashing speeds
- When using spl_autoload_extensions, please order the file extensions from most commonly used to least commonly used, and try to exclude those that are not used at all.
- When using fsockopen or fopen, use the IP address instead of the domain name; if there is only one domain name, use gethostbyname() to obtain the IP address. Using cURL will be faster.
- Replace dynamic content with static content whenever possible.
http://www.bkjia.com/PHPjc/440393.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440393.htmlTechArticleThe tips collected by the author come from a wide range of sources, and the completeness cannot be guaranteed. Due to the large number, these optimization techniques were not tested. Please test it yourself before using it, after all...