PHP performance work begins with finding where time and memory go. A slow page may spend most of its time waiting for SQL or a remote service rather than executing PHP expressions. OPcache helps by reusing compiled PHP bytecode, avoiding repeated parsing and compilation in supported runtimes. It does not cache your database rows or the finished page automatically. This reference explains the distinction, useful measurements, memory limits, and deployment invalidation. You will compare a bounded data-processing design with an unbounded one and learn why enabling a setting without measuring the request is an incomplete optimization.
Measure the operation users experience
Track request latency, error rate, database time, remote-call time, and memory under realistic inputs. An average can hide a slow tail, so examine percentile behavior and worst cases relevant to the product. Compare measurements before and after a change using the same workload and environment. A local five-row database may not reveal a production query problem. Profilers help locate expensive call paths, but profiling overhead can change timing and should be understood. Keep sensitive inputs out of traces. Start with the largest cost rather than rewriting tiny string operations because a microbenchmark suggested one syntax is faster. An optimization is useful when it improves the actual requirement without compromising correctness.
Understand what OPcache stores
PHP normally parses source and compiles it to internal instructions before execution. OPcache stores compiled bytecode in shared memory under its runtime model so later requests can reuse it. It improves that part of the work, not the cost of a slow SQL query, image resize, or HTTP call. OPcache settings and availability differ by PHP installation and interface. CLI caching has its own setting and is not necessarily useful for short one-off commands. Long-running workers have different lifecycle considerations. Inspect effective configuration through protected tooling. Do not expose an OPcache status or reset endpoint publicly, because it can reveal paths or allow disruption. JIT is a separate feature and not a universal improvement for ordinary web workloads.
Plan memory and script capacity
OPcache has configuration for memory consumption, interned strings, and the number of cached script keys. A codebase with many dependencies can need more capacity than a tiny project, but unlimited growth is not a policy. Observe cache fullness, misses, restarts, and the actual application's script count using supported diagnostics. Choose values based on measured deployment behavior and available memory across services. PHP process memory limits and OPcache shared memory are different concerns. A full cache can reduce expected benefits, while excessive allocation wastes capacity. Avoid copying a production setting from another site without knowing its size, worker model, and release pattern. Configuration should be documented as part of the operating environment.
Coordinate code changes and invalidation
Timestamp validation allows OPcache to notice source changes under its checking policy. Disabling validation can improve certain lookup overhead but requires a reliable deployment process that invalidates or restarts the relevant runtime. Otherwise a release can serve stale compiled code. A CLI opcache_reset() does not necessarily clear the separate web-server cache, so use the actual runtime's supported reload or invalidation procedure. Atomic release-directory switches and immutable artifacts can simplify rollout but still need verified cache behavior. Test that a deployed code change is actually active. Do not let an ordinary user trigger cache resets. A documented rollback must also refresh the runtime so the previous artifact's code is the one executing.
Improve expensive application patterns
A query inside a loop can create an N+1 problem, where listing twenty products produces twenty extra queries. Fetch related data in a deliberate joined or batched design when it fits the result shape. Add indexes based on actual predicates and plans rather than every column. Stream large CSV or file results instead of loading them all into arrays. Cache repeated derived data only when you define freshness, ownership, and invalidation. A private account result must not leak through a shared public cache. Compress or resize assets under the appropriate delivery pipeline. Avoid turning every optimization into PHP code when the main cost belongs to database design, network delivery, or frontend assets.
Keep performance changes correct and observable
A faster query that drops authorization predicates is a bug, not a successful optimization. A cache that serves stale stock may violate business rules even if response time improves. Define acceptable freshness and consistency for each cached value. Test correctness under invalidation, missing cache, and concurrent updates. Apply bounded timeouts and concurrency limits to slow external services so one dependency cannot occupy all workers. Record performance results with their workload and limitations. Keep a simple fallback where possible. Run relevant behavior checks after optimization and measure again only when the change or new evidence justifies it. Performance is an operational property of the complete system, not a list of magical PHP settings.
Practice task and worked solution
A product page issues one product query and a separate category query for each of fifty products. Measure query count and latency on a realistic fixture, then design a batched or joined retrieval preserving the intended result shape and authorization. The solution compares before and after with the same data and verifies no product duplication was introduced. Inspect whether OPcache is enabled in the serving runtime, but do not assume it solves the SQL round trips. Document deployment cache invalidation and test a code release under the selected timestamp policy. Keep any status tooling protected and explain the limits of your measurements.
Continue learning
Review PDO, file handling, and Composer.
The OPcache configuration reference documents capacity and timestamp-validation directives.
PHP Performance and OPcache Basics Examples
Each example shows the code, the output it produces and what each part does.
Measure a bounded computation
This CLI example uses hrtime() for elapsed time and memory_get_peak_usage() for the process high-water mark. It does not claim a universal benchmark result.
The arithmetic total is deterministic. Elapsed time and peak process memory depend on the machine, runtime, instrumentation, and other work in the process. This micro-example teaches measurement syntax, not an optimization recommendation.
<?php
$start = hrtime(true);
$total = 0;
for ($number = 1; $number <= 10000; $number++) {
$total += $number;
}
$elapsedMs = (hrtime(true) - $start) / 1_000_000;
echo 'Total: ' . $total . PHP_EOL;
printf("Elapsed: %.3f ms\n", $elapsedMs);
echo 'Peak bytes: ' . memory_get_peak_usage(true) . PHP_EOL;Total: 50005000
Elapsed: environment-dependent milliseconds
Peak bytes: environment-dependent process high-water markPHP Performance and OPcache Basics FAQ
Does OPcache cache SQL results?
No. OPcache caches compiled PHP bytecode, so PHP doesn't have to read and compile your scripts on every request. Query results need a separate cache, such as Redis or Memcached, or better indexes and queries.
Does JIT always speed a website?
No. Measure the actual workload: many requests wait elsewhere, on the database, files or other services, and JIT only speeds up CPU-heavy PHP code such as image processing or complex calculations. Typical web pages see little difference.
Can CLI reset the web cache reliably?
No. The command line and PHP-FPM may use separate caches and runtimes, so opcache_reset() from a CLI script clears only the CLI's own cache. Reset the web cache through the web server, by reloading PHP-FPM or calling a protected endpoint.
Is a microbenchmark enough?
No. It only measures its narrow operation under that environment, often with warm caches and unrealistic data. Profile real requests with production-like data, using tools such as Xdebug's profiler or an application performance monitor, to find what actually costs time.
PHP Performance and OPcache Basics Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Most request time is in repeated SQL queries. What is the best first focus?
PHP Performance and OPcache Basics Quiz
2 questions to check what you learned.
What does OPcache primarily cache?
- Every database row
- Compiled PHP bytecode
- All finished HTML automatically
- SMTP delivery receipts
What is required when timestamp validation is disabled?
- Nothing; new source is always noticed
- A public reset button
- A reliable runtime invalidation or restart policy during release
- Deleting SQL indexes