PHP performance problems often come from a small number of expensive operations: repeated database queries, large object graphs, serialization, network calls, or inefficient loops over large data sets.
Establish a reproducible workload
Choose representative requests and data volumes. Measure wall-clock time, CPU time, memory peak, database time, and external service latency. Keep environment and cache state consistent when comparing runs.
Use profiling tools
A profiler can show function call counts, inclusive time, memory allocation, and call relationships. Application tracing can reveal time spent outside PHP in SQL queries or HTTP requests. Use production-safe sampling where full tracing would add too much overhead.
Optimize the dominant cost
If the request spends most of its time waiting for a database query, rewriting a PHP loop will not materially improve latency. If memory peaks are high, inspect large arrays, file buffering, and unnecessary copies.
Verify the result
Repeat the same workload after the change. Add a regression test or performance check for important paths.
Checklist
- Profile representative requests and data.
- Separate CPU, memory, SQL, and network time.
- Fix the largest measured cost first.
- Compare before and after under similar conditions.
- Keep profiling overhead controlled in production.