§2024-07-08
OPcache is a PHP extension that improves the performance of PHP scripts by storing precompiled script bytecode in shared memory, thus eliminating the need for PHP to load and parse scripts on each request. This can significantly reduce the overhead of PHP execution and improve response times for web applications.
-
Key Features of OPcache:
- Bytecode Caching: Stores the compiled bytecode of PHP scripts in memory, reducing the time needed for script execution.
- Optimization: Optimizes PHP code for faster execution.
- Memory Management: Manages memory efficiently to cache more scripts.
- Configuration Options: Provides various settings to control caching behavior.
-
Common opcache Directives in php.ini:
- enable OPcache
- opcache.enable=1
- Enable OPcache for the CLI (Command Line Interface)
- opcache.enable_cli=1
- Memory Consumption
- opcache.memory_consumption=128
- Sets the maximum amount of memory (in megabytes) that OPcache can use to store precompiled scripts.
- Interned Strings Buffer
- opcache.interned_strings_buffer=8
- Interned Strings Buffer
- Amount of memory for interned strings in megabytes.
- Maximum Accelerated Files
- opcache.max_accelerated_files=10000
- Maximum Accelerated Files
- Maximum number of keys (scripts) in the OPcache hash table.
- Revalidate Frequency
- opcache.revalidate_freq=2 How often (in seconds) to check for script updates. Setting it to 0 will check on every request (useful in development). File Cache
- Revalidate Frequency
- enable OPcache
ini コードをコピーする opcache.file_cache=/path/to/cache Enables file-based caching to supplement memory-based caching. Validate Timestamps
ini コードをコピーする opcache.validate_timestamps=1 If enabled, OPcache will check script timestamps and recompile scripts if they have been updated. Logging Errors
ini コードをコピーする opcache.log_verbosity_level=3 Sets the verbosity level for OPcache error logging.
- Example Configuration in php.ini:
[opcache]
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.file_cache=/tmp
opcache.validate_timestamps=1
opcache.log_verbosity_level=3
- Enabling OPcache:
To enable OPcache, you need to ensure that the OPcache extension is installed and enabled in your PHP setup. This can usually be done by adding or uncommenting the following line in your php.ini file:
zend_extension=opcache.so
Then restart your web server to apply the changes.
- Monitoring OPcache:
You can monitor OPcache performance and status using various tools and scripts, such as the opcache-status script available in the PHP source repository or third-party monitoring tools like New Relic or Datadog.
Enabling and properly configuring OPcache can lead to significant performance improvements for your PHP applications, making it a valuable tool for optimizing server response times and resource usage.