Table of Contents
1. Overview" >1. Overview
2. Introduction to OPCache " >2. Introduction to OPCache
5. OPCache update strategy " >5. OPCache update strategy
6. OPCache configuration" >6. OPCache configuration
Home Backend Development PHP Tutorial In-depth analysis of how PHP Opcache works

In-depth analysis of how PHP Opcache works

Jan 05, 2022 pm 02:01 PM
opcache php

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.

1. Overview

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

  • Start PHP-FPM. PHP-FPM supports two communication modes: TCP socket and Unix socket;
  • PHP-FPM will start two types of processes: Master process and Worker process, the former is responsible for monitoring ports, allocating tasks, and managing Worker processes; the latter is the PHP cgi program, responsible for interpreting, compiling, and executing PHP scripts.
  • Start Nginx. First, the ngx_http_fastcgi_module module will be loaded to initialize the FastCGI execution environment and implement the FastCGI protocol request proxy
  • It should be noted here: the fastcgi worker process (cgi process) is managed by PHP-FPM. Not Nginx. Nginx is just a proxy

Second step: Request => Nginx

  • Nginx receives the request and selects a suitable handler based on the location configuration
  • Here is the handler for proxy PHP

The third step: Nginx => PHP-FPM

  • Nginx translates the request Fastcgi request
  • Send to PHP-FPM master process through TCP socket/Unix Socket

Step 4: PHP-FPM Master => Worker

  • PHP-FPM master process receives the request
  • Assigns the Worker process to execute the PHP script. Ifthere is no idle Worker, a 502 error is returned
  • The Worker (php-cgi) process executes the PHP script. If times out, a 504 error will be returned
  • The processing is completed and the result will be returned

Step 5: PHP-FPM Worker => Master => Nginx

  • PHP-FPM Worker process returns the processing result and closes the connection. Waiting for the next request
  • PHP-FPM Master process returns the processing result through Socket
  • Nginx Handler sequentially sends each response buffer to the first filter → the second → and so on → finally The response is sent to the client

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";
}
Copy after login

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: formerly known as Zend Optimizer, it is an open source component of Zend Server; official product, highly recommended
  • APC: Alternative PHP Cache is an open and free PHP opcode caching component, used to cache and optimize PHP intermediate code; it is no longer updated and is not recommended
  • APCu: It is a branch of APC, shares memory, caches user data, and cannot cache opcode , can be used with Opcache
  • eAccelerate: also not updated, not recommended
  • xCache: no longer recommended

2. Introduction to OPCache

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:

  • OPCode
  • Interned String, such as comments, variable names, etc.

##3. OPCache principle

The main mechanism of OPCache caching is:

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:

    System-V shm API: System V shared memory,
    • sysv shm is persistent. Unless it is explicitly deleted by a process, it always exists in memory until the system is shut down;
  • mmap API:
    • The memory mapped by mmap is not persistent. If the process is closed, the mapping will become invalid unless it has been mapped to a file in advance.
    • Memory mapping mechanism mmap is a POSIX standard system call. It has two types: anonymous mapping and file mapping.
    • One of the great advantages of mmap is that it maps files to the address space of the process.
    • Avoids the need for data to be transferred from the user buffer to The copy process of the kernel page cache buffer;
    • Of course, another advantage is that frequent read/write system calls are not required
  • POSIX API: System V shared memory is outdated, POSIX shared memory provides an API that is simpler to use and more rationally designed.
  • Unix socket API
OPCache uses the first three shared memory mechanisms, depending on the configuration or Default mmap memory sharing mode.

Based on the scenario of PHP bytecode caching, OPCache's memory management design is very simple, with fast reading and writing, no memory release, and expired data is set to Wasted.

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. OPCache cache interpretation

OPCache is the official Opcode cache solution. After PHP5.5 version, it has been packaged into PHP source code and released together.

It caches the bytecode and data generated by PHP compilation into shared memory. At each request, the compiled opcode is directly read from the cache and executed.

Improve the running efficiency of PHP by saving the script compilation process.

If you are using the APC extension to do the same job, it is now strongly recommended to use OPCache instead, especially in PHP7.

4.1 OPCode cache

Opcache will cache OPCode and the following content:

  • Function involved in PHP script
  • Class defined in PHP script
  • PHP script file path
  • PHP script OPArray
  • PHP The structure/content of the script itself

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.

5. OPCache update strategy

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?

  • Don’t release code during peak periods, this is a rule to be followed under any circumstances
  • Code warm-up, such as using The script adjusts PHP access URLs in batches, or uses the API exposed by OPCache such as opcache_compile_file() for compilation and caching

6. OPCache configuration

6.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
  • ##opcache.max_wasted_percentage=5 Wasted memory Upper limit, in percent. If this limit is reached, OPcache will generate a restart event. Default5

6.2 Number and size of files allowed to be cached

  • opcache .max_accelerated_files=2000 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
  • opcache.max_file_size=0 Maximum cached file size in bytes. Set to 0 to cache all files. Default value 0

6.3 Comment related cache

  • opcache.load_comments 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.
  • opcache.fast_shutdown 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!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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.

See all articles