PHP caching basics

Warning: This post is outdated and may not reflect the current state of the art

PHP is quite fast, and with the release of PHP 7, its running speed is greatly improved, sometimes the average speed is twice that of PHP 5.5. HHVM is sometimes even faster. In other words, caching is critical to the speed of PHP applications.

OP cache

OPCache is a special caching mechanism used to store pre-compiled versions of PHP files. After execution, a PHP file is compiled into bytecode, and once this process is completed, the bytecode is executed.

99.9% of the opcodes are the same within a few days, because a file may not change for months, but by default, PHP will be recompiled every time.

To improve this, please use OPCache. OPCache improves the performance of PHP by storing pre-compiled script bytecode in shared memory without requiring PHP to load and parse the script on every request.

Since PHP 5.5, it has been bundled in the kernel, just installing it can make us get a great speed improvement, this is nonsense.

OPCache documentation

Copper copper alloy

APCu is an old APC without opcode cache, and it is now officially provided by OPCache. It is a user cache, which means that it must be explicitly used by the PHP code to take advantage of it, and OPCache can do all the work after installation.

When performing expensive operations (such as reading files or obtaining network resources), the results can be stored in the user cache to speed up future requests for the same object.

The only disadvantage of APCu is that it is local to the computer running it and local to the PHP process and system. This means that if you use PHP as a FastCGI process (such as Nginx and php-fpm), each PHP process will have its own cache.

Unless you want to run your application on multiple servers or processes, that's fine. Otherwise, Memcached and Redis may be a good solution.

Use APCu

<?php
function getData() {
    $data = apc_fetch('some_data');
    if ($data === false) {
        $data = $this->getSomeData();
        apc_add('some_data', $data);
    }
    return $data;
}
?>

APCu documentation

APC, XCache, Memcached, Redis, etc.

Since OPcache is now built-in, and the key-value cache is now part of APCu, APC is no longer important. It is no longer recommended to use XCache, please use APCu instead. Memcached and Redis can replace APCu, which is not convenient on a stand-alone system, because they must be set separately, and there is no real advantage over APCu, but if you run multiple PHP processes or set up a system network (because they can all rely on) , It is very convenient in the central cache location.