PHP optimization details, php optimization details _ PHP Tutorial

Source: Internet
Author: User
Tags type casting
PHP optimization details, php optimization details. PHP optimization details, php optimization details I collected these skills from a wide range of sources, integrity cannot be guaranteed. These optimization techniques were not tested due to a large number of results. Please take a look at the details about PHP optimization and php optimization.

These techniques collected by the author have a wide range of sources, and the integrity cannot be guaranteed. These optimization techniques were not tested due to a large number of results. You can test these skills on your own before using them. after all, whether these skills can be used depends on the unique environment of PHP.

Finding the Bottleneck)

In the face of a performance problem, the first step is always to find the cause of the problem, rather than looking at the tip list. Find out the cause of the bottleneck, find the target and implement the repair, and then re-test. Finding a bottleneck is only the first step in the long journey. there are some common skills here, hoping to help you find the bottleneck in the most important first step.

  • Use Monitoring methods (such as monitoring treasures) to perform benchmark and monitoring, and the network, especially the network condition, is changing rapidly. if you do well, you can find the bottleneck in five minutes.
  • Analyze the code. You must understand that the code is the most time-consuming, and pay more attention to it in these areas.
  • To find the bottleneck, check each Resource Request (such as network, CPU, memory, shared memory, file system, process management, network connection, etc ......)
  • First, perform benchmark on the iterative structure and complex code.
  • Use real data for real testing under real loads. of course, it is best to use the product server.
Cache)

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

  • Use the OPCODE cache so that the script will not be re-compiled every time it is accessed. For example, enable Windows cache extension on windows. 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 ()
Compile vs. Explanation (Compiling vs. Interpreting)

Compile the PHP source code into a machine code. Dynamic interpretation executes the same compilation, but it is executed by line. Compiling to opcode is a compromise. it can translate the PHP source code into opcode, and then convert opcode into a machine code. The following are tips for compilation and interpretation:

  • Compile the PHP code into a machine code before going online. Although opcode caching is not the best choice, it is still better than interpretation. Alternatively, you can compile the PHP code into a C extension.
  • PHP opcode compiler (bcompiler) is not available in the product environment, but developers should focus on http://php.net/manual/en/book.bcompiler.php.
Code slimming)

The smaller the number, the larger the block size. These tips can help reduce code:

  • Fewer features per page
  • Clear webpage content
  • If interpreted, clear comments and other spaces
  • Reduce database queries
Multithreading and Multiprocessing)

From fast to slow:

PHP does not support multithreading, but can use C to write multiple-threaded PHP extensions. There are some ways to use multi-process or simulate multi-process, but the support is not very good, maybe it is slower than a single process.

String (Strings)

String processing is one of the most common operations in most programming languages. Here are some tips to help us make string processing faster:

  • PHP connection operations (vertex operations) are the fastest connection method.
  • Avoid link strings in print. separate strings with commas and use ECHO
  • Use str _ prefix string functions to replace regular expressions.
  • Pos () is faster than preg_mach () and ereg ()
  • Some people say that the string enclosed in single quotes is faster than that enclosed in double quotes, and some people say there is no difference. Of course, if you want to reference a variable in a string, single quotation marks are useless.
  • If you want to determine whether the length of a string is smaller than a certain value (for example, 5), use isset ($ s [4]) <5.
  • To connect multiple small strings to a large string, enable the ob_start output cache first, and then output the data to the buffer using echo. Then, use ob_get_contents to read the string.
Regular expression (Regular Expressions)

Regular expressions provide flexible and diverse methods for comparing and searching strings. The performance overhead of a single regular expression is not low.

  • Use the string processing function prefixed with STR _ to replace the regular expression.
  • [Aeiou] is not used (a | e | I | o | u)
  • The simpler the regular expression, the faster the speed.
  • Try not to set the PCRE_DOTALL modifier
  • Use ^. * instead .*
  • Simplified regular expressions. (For example, use a * instead of (a + )*
Iteration structure (Iteration Constructs (for, while ))

Iteration (repetition, loop) is the most basic structured programming method, and it is hard to imagine programs that do not use it. Here are some tips to help us improve the performance of the iteration structure:

  • Try to remove the code out of the loop (function call, SQL query, etc ......)
  • Use I = maxval; while (I-) instead of for (I = 0; I
  • Use foreach to iterate the set and array
Selection Constructs (if, switch ))

Similar to the iteration structure, the selection structure is also the most basic method for structuring. The following tips may improve performance:

  • In switches and else-if, the columns that frequently appear "true" in the past should be placed in the front. if true is rarely displayed, please back up
  • Some people say that if-else is faster than swtich/case. of course, some people disagree.
  • Replace else if.
Functions and Parameters (Functions & Parameters)

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

  • The object and array are passed by reference, instead of the value.
  • Use inline if it is used only in one place. If it is called in multiple places, consider inline, but pay attention to maintainability
  • Understand the complexity of your function. For example, if similar_text () is O (N ^ 3), the length of the string is doubled and the processing time is increased by 8 times.
  • Do not use "return reference" to improve performance. the engine will automatically optimize it.
  • Call a function in the normal way, instead of using call_user_func_array () or eval ()
Object-Oriented Constructs)

PHP's object-oriented features may affect performance. The following tips help us minimize this impact:

  • Not everything needs to be object-oriented, and the loss of performance may surpass its advantages.
  • Slow object creation
  • If possible, use arrays instead of objects whenever possible.
  • If a method can be static, please declare it statically
  • Function calling is faster than calling a derived class method, and calling a derived class method is faster than calling a base class.
  • Consider copying the most common code in the base class to the derived class, but pay attention to the maintenance risk.
  • Avoid using native getters and setters. If you do not need them, delete them and make them public.
  • When creating complex PHP classes, consider using the single-piece mode
Session Handling)

Creating sessions has many benefits, but sometimes it produces unnecessary performance expenses. The following tips 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 a directory to each user in the virtual host
  • Use memory-based session processing instead of file-based session processing
Type Casting)

Converting from one type to another requires cost

Compression)

Before transmission, compress text and data:

  • Use ob_start () to start the code
  • You can use ob_gzhandler () to download and increase the speed, but pay attention to CPU usage.
  • Apache mod_gzip module can be compressed
Error Handling)

Error handling affects performance. What we can do is:

  • Record error logs. do not use "@" to suppress error reports. blocking has the same effect on performance.
  • Do not only check the error log, but also handle the warning log.
Declaration, definition, and Scope (Declarations, Definitions, & Scope)

Creating a variable, array, or object has an impact on performance:

  • Some people say that declarations and use of global variables/objects are faster than local variables/objects, and some people disagree. Please test before deciding.
  • Declare all variables before using variables. do not declare unused variables.
  • Use $ a [] as much as possible in the loop to avoid using $ a = array (...)
Memory leakage (Memory Leaks)

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

  • Keep releasing resources and do not expect built-in/automatic garbage collection
  • After use, try to unset the variable, especially the resource class and the large array type.
  • 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 does it take time to solve problems that have been solved by others?

  • Understand PHP and its functions and extensions. If you do not know, some existing functions may not be available.
  • Using built-in arrays and string functions is definitely the best performance.
  • The wheel invented by our predecessors does not mean that the best energy absorption in your environment.
Code Optimization)
  • Use an opcode optimizer
  • If it will be interpreted as running, streamline the source code
Use RAM (Using RAM Instead of DASD)

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

  • Move a file to Ramdisk
  • Use memory-based session processing instead of file-based session processing
Use Services (Using Services (e.g., SQL ))

SQL is often used to access relational databases, but our PHP code can access many different services. The following are some access services that need to be kept in mind:

  • Do not ask questions about the server going east over and over again. Use memoization to cache the first result, and then access the result directly to the cache;
  • In SQL, replacing mysql_fetch_assoc () with mysql_fetch_array () can reduce the integer index in the result set. Access the result set by field name without indexing numbers.
  • If the Oracle database does not have enough available memory, increase oci8.default _ prefetch. Set oci8.statement _ cache_size to the number of statements in the application.
  • Replace mysqli_fetch_array () with mysqli_fetch_all () unless the result set is sent to another layer for processing.
Installation and Configuration)

When installing and configuring PHP, consider the following performance:

  • Add more memory
  • Delete competitive applications and services
  • Compile only the needed extensions
  • Statically compile PHP into APACHE
  • Use-O3 CFLAGS to enable all compiler optimizations
  • Only install the required modules
  • Upgrade to the minor version of the latest version. Upgrade the motherboard and wait until the first bug is fixed. of course, do not wait too long.
  • Configure multiple CPU environments
  • Use-enable-inline-optimization
  • Set session. save_handler = mm to compile with-mmto and use shared memory.
  • Use RAM disk
  • Disable resister_global and magic_quotes _*
  • Disable expose_php
  • Disable always_populate_raw_post_data unless you must use it
  • Disable register_argc_argv in non-command line mode.
  • Use PHP only in the. PHP file
  • 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 speed up file/directory access
  • 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
  • Disable register_globals, register_long_arrays, and register_argc_argv. enable auto_globals_jit.
Others (Other)

Some skills are hard to classify:

  • Use include () and require () to avoid using include_once () and require_once ()
  • Use absolute path in include ()/require ()
  • HTML generated by PHP for static HTML is faster.
  • Use ctype_alnum, ctype_alpha, and ctype_digit to replace the regular expression.
  • Use simple servlets or CGI
  • When using code in the product environment, try to write logs as much as possible
  • Use output buffer
  • Use isset ($ a) instead of compare $ a = null; use $ a = null instead of is_nul ($)
  • The script execution TIME is required. read $ _ SERVER ['request _ time'] directly instead of using time ()
  • Use echo to replace print
  • Use pre-auto-increment (++ I) instead of post-auto-increment (I ++). most compilers will optimize it now, but keep this way when they are not optimized.
  • Process XML and use regular expressions instead of DOM or SAX
  • HASH Algorithms: md4, md5, crc32, crc32b, and sha1 are faster than other HASH algorithms.
  • When spl_autoload_extensions is used, the file extension should follow the most common-> the least commonly used order, and eliminate unnecessary objects as much as possible.
  • When fsockopen or fopen is used, IP addresses are used instead of domain names. if there is only one domain name, gethostbyname () can be used to obtain the IP address. CURL is faster.
  • Whenever possible, use static content instead of dynamic content.

Http://www.bkjia.com/PHPjc/1131345.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1131345.htmlTechArticlePHP optimization details, php optimization detailed explanation of the author to collect these skills from a wide range of sources, integrity cannot be guaranteed. These optimization techniques were not tested due to a large number of results. Please visit the official website...

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.