Optimization Tips on PHP Performance

There are countless optimization tips about PHP performance on the Internet, and it is necessary to make a list for reference.

These skills collected by the author come from a wide range of sources, and their completeness cannot be guaranteed. Due to the high volume, these optimization techniques were not tested. Please test it yourself before using it. After all, whether these skills can come in handy depends on the unique environment where PHP is located.

1. Find the bottleneck (Finding the Bottleneck)

When faced with a performance problem , the first step is always to find the cause of the problem , not to look at a list of tricks. Figure out what caused the bottleneck, find the target and implement the fix, then retest. Finding the bottleneck is only the first step in the Long March. Here are some common techniques, hoping to help you find the bottleneck in the most important first step.

  • Use monitoring methods (such as monitoring treasure) to conduct benchmark (benchmark test) and monitoring. The network, especially the network status, changes rapidly. If done well, you can find the bottleneck in 5 minutes.
  • Dissect the code. It is necessary to understand which parts of the code take the most time, and pay more attention to these places.
  • To find bottlenecks, check each resource request (e.g., network, CPU, memory, shared memory, filesystem, process management, network connections, etc...)
  • First benchmark the iterative structure and complex code
  • Do real tests with real data under real load , preferably with a production server if you can.

2. Caching

Some people think that caching is one of the most effective solutions to performance problems , try these:

  • Use OPCODE (operation code) caching so that the script is not recompiled every time it is accessed. For example: enable the windows cache extension on the Windows platform. Can cache opcode, file, relative path, session data and user data.
  • Consider using a distributed cache in a multi-server environment
  • Call imap_headers() before calling imap_header()

3. Compiling vs. Interpreting (Compiling vs. Interpreting)

Compile PHP source code into machine code. Dynamic interpretation performs the same compilation, but it does it line by line. Compiling to opcode is a compromise choice. It can translate PHP source code into opcode, and then convert opcode into machine code. The following are related tips about compiling and interpreting:

  • Compile PHP code to machine code before going live. Although the opcode cache is not the best choice, it is still better than the interpreted one. Alternatively, consider compiling the PHP code into a C extension.
  • PHP's opcode compiler (bcompiler) is not yet available in production, but developers should follow http://php.net/manual/en/book.bcompiler.php

4. Content Reduction

Fewer and faster. These tips can help reduce code:

  • Fewer features per page
  • Clean up web content
  • If executed interpretively, clean up comments and other whitespace
  • Reduce database queries

5. Multithreading & Multiprocessing

From fast to slow are:

  • Multi-threaded (in a single process)
  • Multiprocessing (eg, pcntl_fork, scheduled tasks)
  • single process (line after line)

PHP does not support multithreading, but you can write multithreaded PHP extensions in C. There are some ways to use multiple processes or simulate multiple processes, but the support is not very good, and it may be slower than a single process.

6. Strings

String manipulation is one of the most commonly used operations in most programming languages. Here are some tricks that can help us make string processing a little faster:

  • PHP's connection operation (point operation) is the fastest connection method
  • Avoid concatenating strings in print, use ECHO after splitting with commas
  • Use str_ prefixed string functions instead of regular expressions whenever possible
  • pos() is faster than both preg_mach() and ereg()
  • Some say it's faster to wrap a string in single quotes than double quotes, some say it makes no difference. Of course, if you want to quote variables in strings, 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 ob_start output buffer first, then use echo to output to the buffer, and use ob_get_contents to read the string after completion

7. Regular Expressions

Regular expressions bring us flexible and diverse methods of comparing and finding strings, but their performance overhead is really not low

  • Whenever possible, use STR_ prefixed string processing functions instead of regular expressions
  • Not (a|e|i|o|u) using [aeiou]
  • Simpler regular expressions are faster
  • Do not set the PCRE_DOTALL modifier when possible
  • Use ^. instead of .
  • Simplify regular expressions. (e.g. use a instead of (a+)

8. Iteration Constructs (for, while)

Iteration (repetition, looping) is the most fundamental method of structured programming , and it's hard to imagine a program that doesn't use it. Here are some tricks that help us improve the performance of iterative structures:

  • Move code out of loops as much as possible (function calls, SQL queries, etc...)
  • Use i=maxval;while(i–) instead of for(i=0;i<maxval;i++), which can reduce one operation, and it is more obvious if maxval is a function call.
  • Using foreach to iterate collections and arrays

9. Selection Constructs (if, switch)

Like the iteration structure, the selection structure is also the most basic structured programming method . The following techniques may improve performance:

  • In switches and else-if, the ones that frequently appear true recently should be listed first, and the ones that rarely appear true should be listed later
  • Some people say that if-else is faster than swtich/case, of course, some people disagree.
  • Replace else if with elseif.

10. Functions & Parameters

Breaking down a function's code into smaller function codes removes redundancy and makes the code more readable , but at what cost? Here are some tips to help you use functions better:

Objects and arrays are passed by reference, not by value.
If only used in one place, use inline. If called in multiple places, consider inlining, but be careful about maintainability. Understand
the complexity of the functions you use. For example, similar_text() is O(N^3), which means that the length of the string is doubled, and the processing time will be increased by 8 times.
Do not use "return reference" to improve performance, the engine will automatically optimize it.
Call the function in the normal way instead of using call_user_func_array() or eval()

11. Object-Oriented Constructs

The object-oriented nature of PHP may affect performance . The following tips can help us minimize this effect:

  • Not everything needs to be OO, and the performance penalty may outweigh the benefits
  • Object creation is slower
  • Whenever possible, use arrays instead of objects
  • If a method can be made static, 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 from base classes into derived classes, but be aware of maintenance pitfalls
  • Avoid native getters and setters. Remove if they are not needed and the properties are public
  • When creating complex PHP classes, consider using the Singleton pattern

12. Session Handling

Creating sessions has many benefits, but sometimes creates unnecessary performance overhead . The following tips can help us minimize performance overhead:

  • Do not 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

13. Type Casting

Converting from one type to another requires a cost

14. Compression

Compress text and data before transmission:

  • Use ob_start() at the beginning of the code
  • Use ob_gzhandler() to download faster, but pay attention to CPU overhead
  • Apache's mod_gzip module can compress even

15. Error Handling

Error handling affects performance . What we can do is:

  • Record error logs, don't use "@" to suppress error reports, suppression has an impact on performance
  • Don't just check the error log, the warning log needs to be dealt with

16. Declarations, Definitions, & Scope

Creating a variable, array, or object has performance implications:

  • Some people say that declaring and using global variables/objects is faster than local variables/objects, and some people object. Please test and decide.
  • Declare all variables before using them, do not declare unused variables
  • Use a[] whenever possible in loops , avoid a[], avoida [ ] , avoid using a=array(…)

17. Memory Leaks

This is definitely a problem if memory is allocated and not freed :

  • Insist on freeing resources, don't count on built-in/automatic garbage collection
  • Try to unset (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()

18. Don't reinvent the wheel (Don't Reinvent the Wheel)

Why spend your time solving problems that others have already solved?

  • Get to know PHP, its features and extensions. You may not be able to take advantage of some out-of-the-box features if you don't know
  • Use the built-in array and string functions, they are definitely the best performers.
  • The wheel invented by the predecessors does not mean that the energy absorption is the best in your environment, test more

19. Code Optimization

  • Use an opcode optimizer
  • If it will be interpreted and run, please simplify the source code

20, Using RAM Instead of DASD

RAM is much, much faster than disk , and using RAM can improve some performance:

  • Move files to Ramdisk
  • Use memory-based session processing instead of file-based session processing

21. Using Services (eg, SQL)

SQL is often used to access relational databases, but our PHP code can access many different services. Here are some access services to keep in mind:

  • Don't ask the server to go east over and over again. Use memoization to cache the first result, and then go straight to the cache after accessing;
  • In SQL, use mysql_fetch_assoc() instead of mysql_fetch_array() to reduce integer indexes in the result set. Access the result set by field name instead of index number.
  • For Oracle databases, increase oci8.default_prefetch if there is not enough memory available. Set oci8.statement_cache_size to the number of statements in the application
  • Please use mysqli_fetch_array() instead of mysqli_fetch_all(), unless the result set will be sent to another layer for processing.

22. Installation & Configuration

When installing and configuring PHP, please consider performance:

  • add more memory
  • Remove competing apps and services
  • Compile only the extensions you need
  • Compile PHP statically into APACHE
  • Use -O3 CFLAGS to enable all compiler optimizations
  • Only install the modules you need
  • Upgrade to the latest minor version. Mainboard upgrade, wait until the first bug is fixed, of course, don't wait too long
  • Configure for a multi-CPU environment
  • 使用 -enable-inline-optimization
  • Set session.save_handler=mm, compile with -with-mmto, use shared memory
  • use RAM disk
  • Turn off resister_global and magic_quotes_*
  • close expose_php
  • Disable always_populate_raw_post_data unless you must use it
  • Please close 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
  • CPU optimization with -march, -mcpu, -msse, -mmmx, and -mfpmath=sseto
  • Replace libmysql, mysqli extension and PDO MYSQL driver with MySQL native driver (mysqlnd)
  • Disable register_globals, register_long_arrays and register_argc_argv. Enable auto_globals_jit.

23. Other

There are also some tricks that are harder to categorize:

  • 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 the production environment, write logs as much as possible
  • use output buffering
  • Please use isset( a ) instead of compare a) instead of comparea ) instead of comparing a==null; please usea === null instead of isnul (a===null instead of is_nul(a===n u ll instead of i snul(a)
  • Need 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 optimize now, but when they don't, keep it that way.
  • To 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 follow the order of most commonly used -> least commonly used file extensions, 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.
  • Whenever possible, replace dynamic content with static content.

Guess you like

Origin blog.csdn.net/heshihu2019/article/details/132070415