Table of Contents
Finding the Bottleneck
Caching
Compiling vs. Interpreting
Code weight loss (Content Reduction)
Multithreading & Multiprocessing
Strings
Regular Expressions
Iteration Constructs (for, while))
Selection Constructs (if, switch)
Functions & Parameters
Object-Oriented Constructs
Session Handling
Type Casting
Compression
Error Handling
Declarations, Definitions, & Scope
Memory Leaks
Don’t Reinvent the Wheel
Code Optimization
Using RAM Instead of DASD
Using Services (e.g., SQL)
Installation & Configuration
Other
Home Backend Development PHP Tutorial Detailed explanation of PHP optimization_PHP tutorial

Detailed explanation of PHP optimization_PHP tutorial

Jul 20, 2016 am 11:13 AM
php cannot optimization ensure integrity Skill collect quantity source of Detailed explanation

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.

www.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...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles