PHP Opcache Optimization Acceleration

Source: Internet
Author: User
Tags php script
Opcache is a way to avoid the overhead of loading and parsing PHP scripts by storing the bytecode that is precompiled by the parsed PHP script in shared memory, and the parser can read the cached bytecode directly from the shared memory, thus greatly improving the efficiency of PHP execution. PS: It needs to be differentiated from the xcache mechanism, and its use is described in the following summary.

· How to Install

· How to configure

· How to use

· Display analysis

· Precautions

First, how to install

In PHP 5.5.0 and subsequent versions, PHP has embedded the Opcache functionality in the release version, which is not enabled by default Opcache acceleration, requiring developers to add or annotate Opcache related configurations in php.ini. For previous versions, Opcache can be installed and configured as a PECL expansion library.

Note:

If you use the--disable-all parameter to disable the build of the default extension, you must use the--enable-opcache option to turn on Opcache.

Second, how to configure

Ini:

[Opcache]

; Start opcode cache

Opcache.enable=1

; php boot opcode cache for CLI-supported versions is typically used for testing and debugging

Opcache.enable_cli=1

; Shared memory size in megabytes

opcache.memory_consumption=128

; Store temporary string cache size in mb,php5.3.0 previously ignored for this configuration

Opcache.interned_strings_buffer=8

; The maximum number of cache files, less than 100% hit rate, you can try to increase this value

opcache.max_accelerated_files=4000

; Check the file modification time within a certain time, here set the check time period, the default is 2, the unit is seconds

Opcache.revalidate_freq=60

; Turns on fast stop and resume events, relies on the memory management module of the Zend Engine, frees the memory of all request variables at once, instead of freeing the memory block in turn

Opcache.fast_shutdown=1

Enable the ability to check the existence and readability of PHP scripts, regardless of whether the file has been cached, will check the opcode cache, can improve performance. However, if the Opcache.validate_timestamps option is disabled, there may be a risk of returning stale data.

Opcache.enable_file_override=1

; Expand Library So file association load

Zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20131226/opcache.so

Note:

The configuration items listed above are commonly used and important configuration items, which are more than the above configuration items.

Third, how to use

In fact, the use of Opcache is mainly embodied in the several functions it provides:

1, Opcache_get_configuration;

Form: Array opcache_get_configuration (void);

Gets the cached configuration information for the setting, returning the configuration information, blacklist, and version number as an array.

2, Opcache_get_status;

Form: Array opcache_get_status (void);

Gets the cache state information for the setting.

3, Opcache_invalidate;

Form: Boolean opcache_invalidate (String);

The function is to invalidate the byte-code cache for the specified script. If force is not set or is passed FALSE, the script's cache will be invalidated only if the script is modified longer than the corresponding bytecode.

4, Opcache_reset;

Form: Boolean opcache_reset (void);

The function resets the entire byte-code cache. After calling Opcache_reset (), all the scripts will be re-loaded and re-parsed the next time they are clicked.

5, Opcache_compile_file;

Form: Boolean opcache_compile_file (String);

You can compile and cache the script without running it.

6, opcache_is_script_cached

Form: Boolean opcache_is_script_cached (String);

Determines whether a script has been cached to Opcache.

Below I write a PHP script, which includes the encapsulation of several functions above, so as to facilitate future maintenance and management of Opcache, as follows:

<?php/** * This file is encapsulated in several * functions of the Opcache Optimizer, as a tool script using */if (!extension_loaded ("Zendopcache")) {echo "do nothave th e Zend opcache extension loaded, please open it up,then retry! ";} /** * Function Action Encapsulation class * Array form results, will be returned in JSON format, do not do the display on the processing * Here is the main process of affecting the Opcache Cache state operation, for viewing * opcache indicators of processing, can view the project: Opcache-status * *      Class opcachescriptmodel{private $_configuration;      Private $_status;            function __construct () {$this->_configuration =opcache_get_configuration ();      $this->_status =opcache_get_status ();      }//Get configuration information public Function Getconfigdatas () {echo json_encode ($this->_configuration);      }//Get status information public function Getstatusdatas () {echo json_encode ($this->_status);      }//Specifies a script file byte code cache fails public function invalidate ($script) {return opcache_invalidate ($script);      }//Resets or clears the entire byte-code cache data Public Function reset () {return opcache_reset (); }//Without running, you can compile and cacheScript Public Function compile ($file) {return opcache_compile_file ($file); }//Determine if a script has been cached to Opcache public function iscached ($script) {return opcache_is_script_cached ($script)      ;      }}//Get Object function Getopcachedatamodel () {//Initialize object $dataModel = NULL;      if (NULL = = $dataModel) {$dataModel = new Opcachescriptmodel (); } return $dataModel;}? >

The above script tool is relatively simple, can be placed in the project or alone as a tool to use, when necessary to parse the compilation, in fact, the following display analysis of open source projects, but also using the above API functions, but it will get the data in a graphical form of display, so more intuitive, please continue to look down.

Four, display analysis

We know that the PHP script execution mechanism is that the parser parses the php script file and resolves it to bytecode data, and the function of the Opcache optimizer is to cache the parsed bytecode data so that it can be read directly from the cache without having to repeat the loading and parsing of PHP scripts every time. So for the use of opcache, we generally only need to do two things:

1, the use of Opcache Optimizer, speed up the execution of PHP programs;

2, through the Opcache indicators parameters, real-time understanding of the current PHP program performance status;

So how do we look at and analyze the current opcache acceleration effect? The answer is that you can use the Open source project on GitHub: Https://github.com/rlerdorf/opcache-status

Put the downloaded items into the current Web server root directory, direct access, first look at the effect:


As seen from the above and the project files, the Opcache tool is a simplified GUI version that can be used to clearly understand and analyze the following:

1, the use of the cache, the remaining situation and memory waste and proportion;

2. The cache keys, the remaining keys number;

3, the number of cache hits and misses;

4. Cache configuration, status, and cache capture scripts;

5, the cached script file, the View form divides the visual display;

Well, Opcache's visualization is here, here are a few points to watch out for.

Five, matters needing attention

1, not recommended XCache and Opcache simultaneously enable PHP optimization;

Because PHP 5.5.0 and subsequent versions have embedded support for Opcache, PHP is aware of its importance, and using Opcache is a better choice than a third-party PHP optimizer like XCache. In addition, if both exist, the cache hits of the Opcache are greatly reduced and unnecessary overhead is added.

2, not recommended in the development process to open Opcache

The reason is obvious, after Opcache is turned on, the developer's modified content is not immediately visible and effective, because it is affected by opcache.revalidate_freq=60, so it is recommended to test performance after development and testing to open the test, of course, Production environment has always been open Opcache oh.

3. It is not recommended to set the Opcache indicator too large

Opcache each indicator configuration size or whether open, need to combine the actual needs of the project and opcache the official recommendations of the configuration, the actual situation of the project analysis, can be combined with the above fourth part of the visual cache information analysis and adjustment.

4, not recommended long-term use of the old version of Opcache

It is recommended to pay close attention to Opcache website dynamic, real-time understanding of its bugs repair, function optimization and new features, in order to better apply it in their own projects.

5, not recommended in the production environment, the above-mentioned open source project into the Web service root directory

The reason is simple, because this open source project does not do access restrictions and security processing, that is, anyone who can access the extranet, as long as they know the access address can be directly accessible, so it is not secure. Generally, this open source tool only helps visualize the performance of PHP, which is typically used during the development debugging phase. If you want to start working in a production environment, you have to do the security restrictions.

Related Article

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.