PHP optimization detailed, PHP optimization _php tutorial

Source: Internet
Author: User
Tags benchmark php class php source code

PHP optimization detailed, PHP optimization


The author collects these techniques from a wide range of sources, and the completeness is not guaranteed. These optimization techniques have not been tested due to the large number. Please crossing to test yourself before use, after all, whether these skills can be useful, or need to be determined by the unique environment in which PHP resides.

Find bottlenecks (finding the bottleneck)

In the face of a performance problem, the first step is always to find the cause of the problem, not to look at the list of tricks. Figure out what's causing the bottleneck, find the target and implement the fix, and then re-test it. Finding bottlenecks is only the first step in Long March, and here are some common tips to help you find bottlenecks in the most important first steps.

    • Using monitoring methods (such as surveillance treasure), benchmark and monitoring, the network, especially the network situation is changing rapidly, well done 5 minutes can find bottlenecks.
    • Anatomy code. It's important to understand that part of the code takes the most time and takes a lot of attention.
    • To find bottlenecks, check each resource request (for example, Network, CPU, memory, shared memory, file system, process management, network connection, and so on ...). )
    • Benchmark the iterative structure and the complex code first
    • Real-world testing with real data under real load, of course, if it is best to use a product server.

Cache (Caching)

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

    • Use the opcode (opcode) cache so that the script does not recompile once every access. For example, enable Windows cache extensions on the Windows platform. You can cache opcode, files, relative paths, session data, and user data.
    • Consider using distributed caching in a multi-server environment
    • Call Imap_headers () before calling Imap_header ()

Compilation vs. interpretation (compiling vs. interpreting)

Compile the PHP source into machine code. The dynamic interpretation performs the same compilation, but it is performed on a per-line basis. Compile to opcode is a compromise choice, it can translate php source code into opcode, then opcode to machine code. Here are some tips on compiling and interpreting:

    • Compile the PHP code into machine code before going live. The opcode cache, though not the best choice, is still more powerful than the explanatory model. Or, consider compiling the PHP code into a C extension.
    • php's opcode compiler (Bcompiler) is not yet available in the production environment, but developers should focus on http://php.net/manual/en/book.bcompiler.php.

Code weight loss (Content Reduction)

The less the more The block. These tips can help reduce the code:

    • Fewer features per page
    • Clean up Web content
    • If interpreted type is executed, clean up comments and other whitespace
    • Reduce database queries

Multi-threaded and multi-process (multithreading & multiprocessing)

From fast to slow in order:

PHP does not support multi-threading, but it can write multithreaded PHP extensions in C. There are ways to use multiple processes or simulate multiple processes, but the support is not very good, perhaps slower than a single process.

String (Strings)

string processing, which is one of the most commonly used operations in most programming languages. Here are some tips to help us make string processing faster:

    • PHP Connection operation (Point operation), is the fastest way to link
    • Avoid linking strings in print, using the echo after splitting with commas
    • Replace regular expressions with string functions that use the STR_ prefix whenever possible
    • POS () is faster than Preg_mach () and Ereg ()
    • Some people say that single quotes wrap strings faster than double quotes, and some say no difference. Of course, if you want to reference a variable in a string, the single quote is out.
    • If you want to determine if the string length is less than a value (for example, 5), use Isset ($s [4]) <5.
    • If you want to concatenate multiple small strings into a large string, try opening the Ob_start output cache first, then using echo to output to the buffer, and use ob_get_contents to read the string after completion.

Regular Expressions (Regular Expressions)

Regular expressions provide a flexible and versatile way to compare and find strings, but his performance overhead is really low.

    • Replace regular expressions with string-handling functions that use the STR_ prefix whenever possible
    • Not using [Aeiou] (A|e|i|o|u)
    • The simpler the regular expression, the faster it gets.
    • Do not set the Pcre_dotall modifier as much as possible
    • Replace with ^.*. *
    • simplifies regular expressions. (e.g. using a * instead of (A +) *

Iterative Structure (iteration constructs (for, while))

Iterative (repetition, looping) is the most basic structured programming method and it is difficult to imagine a program that does not use it. Here are some tips to help us improve the performance of an iterative structure:

    • As much as possible, the code is moved out of the loop (function calls, SQL queries, etc...) )
    • Use I=maxval;while (i –) instead of for (i=0;i<>< li=""><>
    • Iterating over collections and arrays using foreach

Select Structure (Selection constructs (if, switch))

As with the iterative structure, the selection structure is also the most basic method of structural change. The following tips may improve performance:

    • In switches and else-if, you should have a list of the most recent occurrences of true in front, with fewer occurrences of true on the back
    • Some people say if-else faster than swtich/case, of course, there are objections.
    • Replace the else if with ElseIf.

Functions and Parameters (Functions & Parameters)

Decomposing the code of a function into a small function code can eliminate redundancy and make the code readable, but at what cost? Here are some tips to help you better use the function:

    • References are passed out of objects and arrays, not values
    • If used only in one place, use inline. If called in multiple places, consider inline, but be aware of 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 increases by a factor of 8 times times the processing time
    • Do not use "return reference" to improve performance, the engine will automatically optimize it.
    • Call the function in the usual way, instead of using Call_user_func_array () or eval ()

Object-Oriented Architecture (object-oriented constructs)

The object-oriented nature of PHP 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 its merits
    • Slow creation of objects
    • If you can, use arrays instead of objects whenever possible
    • If a method can be static, declare it statically
    • A function call is faster than a derived class method call, and the derived class method calls the Bikita class to call fast
    • Consider copying the most common code in a base class into a derived class, but be aware of the maintainability implications
    • Avoid the use of native getters and setters. If they are not needed, delete and the properties are exposed
    • When creating a complex PHP class, consider using single-piece mode

Session processing (Session handling)

There are many benefits to creating sessions, but sometimes there is no need for performance overhead. The following tips can help us minimize performance costs:

    • Do not use Auto_start
    • Do not enable Use_trans_sid
    • Set session_cache_limited to Private_no_expire
    • Assign your own directory to each user in the virtual host (Vhost)
    • Use memory-based session processing instead of file-based session processing

Type conversion (Casting)

Cost to convert from one type to another

Compression (Compression)

Compress text and data before transferring it:

    • Use Ob_start () at the beginning of the code
    • Use Ob_gzhandler () to download speed, but pay attention to CPU expenditure
    • Apache's Mod_gzip module can be compressed even

Fault handling (Error handling)

Error handling affects performance. What we can do is:

    • Record the error log and stop using "@" to suppress error reporting, which has the same effect on performance
    • Do not check the error log only, warning logs need to be processed

Declaration, definition and scope (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, which is objected to. Please make a test decision again.
    • Declare all variables before using them, and do not declare variables that you do not use
    • Use $a[] as much as possible in the loop, avoiding the use of $a=array (...)

Memory Leak (Leaks)

If memory is not released after allocation, this is definitely a problem:

    • Persist in releasing resources, do not expect self-brought/automated garbage collection
    • Try to unregister (unset) variables after use, especially for resource classes and large array types
    • Close the database connection when you are finished using
    • Every time you use Ob_start (), remember Ob_end_flush () or Ob_end_clean ()

Don't reinvent the wheel (Don ' t reinvent the Wheel)

Why take time to solve problems that others have already solved?

    • Learn about PHP and learn about its capabilities and extensions. If you don't know, you might not be able to take advantage of some off-the-shelf features
    • Using their own array and string functions, they are definitely the best performance.
    • The wheels invented by the predecessors do not mean that sucking energy is the best in your environment, more testing

Code optimization

    • Use a opcode optimizer
    • If it will be interpreted to run, please streamline the source code

Using RAM (using Ram Instead of DASD)

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

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

Using the service (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 of the access services that you need to keep in mind:

    • Do not ask the server to the east of things over and over again. Use the Memoization cache for the first time results and later access to go straight to the cache;
    • In SQL, you can reduce the integer index in the result set by using MYSQL_FETCH_ASSOC () instead of mysql_fetch_array (). Access the result set as a field name without index numbers.
    • 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 your app
    • Replace Mysqli_fetch_all () with Mysqli_fetch_array () unless the result set is sent to another layer for processing.

Install and configure (Installation & configuration)

When installing and configuring PHP, consider performance:

    • Add more memory
    • Remove competitive applications and services
    • Compile only the extensions that are needed
    • To compile PHP statically into Apache
    • Use-o3 cflags to turn on all compiler optimizations
    • Install only the modules you need to use
    • Upgrade to the latest version of the minor version. Motherboard upgrade, wait until the first bug fix, of course, don't wait too long
    • Configuring for multi-CPU environments
    • Using-enable-inline-optimization
    • Set session.save_handler=mm, compile with-with-mmto, use shared memory
    • Using RAM Disk
    • Close Resister_global and magic_quotes_*
    • Close expose_php
    • Close Always_populate_raw_post_data unless you have to use it
    • In non-command line mode, close the REGISTER_ARGC_ARGV
    • Use PHP only in. php files
    • Optimization of parameters for Max_execution_time, Max_input_time, Memory_limit and output_buffering
    • Set the allowoverride in the Apache configuration file to None to elevate the file/directory access speed
    • Use-march,-mcpu,-msse,-MMMX, And-mfpmath=sseto to optimize the CPU
    • Replace Libmysql, Mysqli extension, and PDO MySQL driver with MySQL native driver (mysqlnd)
    • Close Register_globals, Register_long_arrays, and REGISTER_ARGC_ARGV. Turn on Auto_globals_jit.

Others (Other)

Some techniques are difficult to classify:

    • Use include (), require (), avoid using include_once () and require_once ()
    • Using absolute paths in include ()/require ()
    • HTML generated by PHP is faster than static HTML
    • Use Ctype_alnum, Ctype_alpha, and ctype_digit instead of regular expressions
    • Use a simple servlets or CGI
    • When code is used in a production environment, write the log as much as possible
    • Using output buffering
    • Use Isset ($a) instead of comparison $a==null, use $a===null instead of Is_nul ($a)
    • Requires script to start execution time, please read $_server[' request_time '] instead of using timing ()
    • Use echo instead of print
    • The majority of compilers are now optimized for use of pre-increment (++i) instead of post-increment (i++), but keep this in check when they are not optimized.
    • Working with XML, using regular expressions instead of DOM or sax
    • Hash algorithm: MD4, MD5, CRC32, crc32b, SHA1 faster than other hash speeds
    • When using spl_autoload_extensions, use the file extension in the least common order of the most commonly used –>, and try to eliminate the need to do so.
    • Use an IP address instead of a domain name when using Fsockopen or fopen, or use gethostbyname () to obtain an IP address if there is only one domain name. Using curl speed is faster.
    • Whenever possible, replace dynamic content with static content.

http://www.bkjia.com/PHPjc/1131345.html www.bkjia.com true http://www.bkjia.com/PHPjc/1131345.html techarticle PHP optimization in detail, PHP optimization details The author collects these skills from a wide range of sources, integrity is not guaranteed. These optimization techniques have not been tested due to the large number. Would you please crossing in making ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.