In PHP projects, especially in scenarios with high concurrency and large traffic, how to improve the response time of PHP is a very important task.
Opcache is an indispensable component for optimizing PHP performance, especially in projects that apply the PHP framework.
Before understanding the OPCache function, we must first understandPHP-FPM The working mechanism of Nginx, and the mechanism of PHP script interpretation and execution.
1.1 The working mechanism of PHP-FPM Nginx
The request goes from the web browser to Nginx, and then to PHP processing. The total process is as follows Five steps:
Step one: Start the service
Second step: Request => Nginx
The third step: Nginx => PHP-FPM
Step 4: PHP-FPM Master => Worker
Step 5: PHP-FPM Worker => Master => Nginx
1.2 The mechanism of PHP script explanation and execution
After understanding the overall processing flow of PHP Nginx, we Next, let’s take a look at the specific execution process of the PHP script.
First we look at an example:
<?php if (!empty($_POST)) { echo "Response Body POST: ", json_encode($_POST), "\n"; } if (!empty($_GET)) { echo "Response Body GET: ", json_encode($_GET), "\n"; }
Let’s analyze the execution process:
php initializes the execution link, starts the Zend engine, and loads the registered extension module
After initialization, the script file is read, and the Zend engine performs lexical analysis (lex), syntax analysis (bison) on the script file, generates a syntax tree
Zend engine compiles the syntax tree, generates opcode,
Zend engineExecute opcode, return the execution result
In PHP cli mode, each time the PHP script is executed, the four steps will be executed in sequence;
In PHP-FPM mode, step 1) is executed once when PHP-FPM starts and will not be executed in subsequent requests; steps 2)~4) must be executed once for each request;
In fact, the syntax tree and opcode generated in steps 2) and 3) will have the same result every time the same PHP script is run.
In PHP-FPM mode Next, each request must be processed again, which is a huge waste of system resources. So is there any way to optimize it?
Of course, such as:
OPCache is an open and free opcode cache extension officially produced by Zend. It also has code optimization functions, eliminating the overhead of loading and parsing PHP scripts each time.
OPcache extension has been bundled in PHP 5.5.0 and subsequent versions.
Cache two types of content:
Put the compiled operation code into the shared memory and provide it to other processes for access.
This involves the memory sharing mechanism. In addition, all memory resource operations have locking issues. We will explain them one by one.3.1 Shared Memory
UNIX/Linux system provides many ways to share memory between processes:When the Wasted memory is greater than the set value, the OPCache mechanism is automatically restarted, the cache is cleared and regenerated.
3.2 Mutex lock
Any operation of memory resources involves the lock mechanism. Shared memory: Only one process is allowed to perform write operations within a unit time, and multiple processes are allowed to perform read operations; Write operations are performed at the same time, and read operations are not blocked, so that there are very few locked situation. This raises another problem: new code, large traffic scenarios, processes queue up to perform cache opcode operations; repeated writing leads to waste of resources.4.1 OPCode cache
Opcache will cache OPCode and the following content:4.2 Interned String cache
First we need to understand, what is Interned String?
In PHP5.4, the Interned String mechanism was introduced to optimize PHP's storage and processing of strings.
Especially when dealing with large chunks of strings, such as PHP doces, Interned String can optimize memory.
Interned String cached content includes: Variable names, class names, method names, strings, comments, etc.
In PHP-FPM mode, Interned String cache characters are limited to within the Worker process.
And cached in OPCache, the Interned String cached string can be used between Worker processes to save memory.
We need to pay attention to one thing. In PHP development, there are usually large comments, which will also be cached in OPCache.
You can turn off the caching of comments through the configuration of php.ini.
However, in frameworks such as Zend Framework, will reference comments, so whether to turn off the cache of comments needs to be treated differently.
is a cache, which has expiration and update strategies.
The update strategy of OPCache is very simple. The expired data is set to Wasted. When the set value is reached, the cache is cleared and the cache is rebuilt.
Note here: In high-traffic scenarios, rebuilding the cache is a very resource-intensive matter.
OPCache does not prevent other processes from reading when creating the cache.
This will cause a large number of processes to repeatedly create new caches. Therefore, Do not set the OPCache expiration time
Every time new code is released, the cache will be repeatedly created. How to avoid it?
opcache_compile_file()
for compilation and caching6.1 Memory configuration
opcache.preferred_memory_model="mmap"
OPcache preferred memory module. If left blank, OPcache will select the applicable module. Normally, automatic selection will suffice. Optional values include: mmap
, shm
, posix
and win32
. opcache.memory_consumption=64
Shared memory size of OPcache, in megabytes, default 64M
opcache.interned_strings_buffer =4
The memory size used to store temporary strings, in megabytes, default 4M
Wasted memory Upper limit, in percent. If this limit is reached, OPcache will generate a restart event. Default
5
6.2 Number and size of files allowed to be cached
The maximum number of script files that can be stored in the OPcache hash table. The real value is the first prime number found in the prime number set
{ 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } that is greater than or equal to the set value. The minimum value range of the setting value is
200, the maximum value is
100000 before PHP 5.5.6, and
1000000 before PHP 5.5.6 and later. Default value
2000
Maximum cached file size in bytes. Set to 0 to cache all files. Default value 0
6.3 Comment related cache
boolean If disabled, even if the file contains comments, these comment contents will not be loaded. This option can be used together with
opcache.save_comments to load comment content on demand.
boolean If enabled, fast stop resume events will be used. The so-called quick stop resumption event refers to the memory management module that relies on the Zend engine to release the memory of all requested variables at once, rather than releasing each allocated memory block in sequence.
6.4 Second level cache configuration
opcache.file_cache
Configure the second-level cache directory and enable the second-level cache. Enabling second-level cache can improve performance when the SHM memory is full, the server is restarted, or the SHM is reset. The default value is the empty string ""
, which disables file-based caching. opcache.file_cache_only
boolean
Enable or disable opcode caching in shared memory. opcache.file_cache_consistency_checks
boolean
Whether to verify the checksum of the file when loading the script from the file cache. opcache.file_cache_fallback
boolean
On Windows platforms, when a process cannot attach to shared memory, file-based caching is used, that is: opcache.file_cache_only=1
. File caching needs to be enabled explicitly. Recommended study: "PHP Video Tutorial"
The above is the detailed content of In-depth analysis of how PHP Opcache works. For more information, please follow other related articles on the PHP Chinese website!