Skip to content

Reduce CPU and memory usage of PHP

For most PHP apps, high memory usage is a more significant problem than high CPU usage. This is due to PHP’s architecture: each concurrently executing request runs in a separate process and each process consumes additional memory.

Often, high CPU usage is an indirect result of a server running low on memory. When a server’s available memory is low:

  • The kernel needs to constantly move data into and out of swap space.
  • Files need to be directly accessed from disk rather than being read from the operating system’s disk cache.

Identify the cause of high resource usage

Identifying the cause of high resource usage will allow you to fix the problem faster.

Check PHP slow request logs

Check each app’s PHP slow request log to identify apps with slow PHP code.

Check app memory usage

Use the server’s app monitoring dashboards to view an app’s total PHP usage over time.

Check MySQL cache usage

Use the server’s MySQL monitoring dashboards to determine if the MySQL cache size needs to be increased.

Check MySQL slow query log

Check the MySQL slow query log to identify slow queries that are causing PHP requests to be slow and therefore are increasing the number of PHP processes that are running.

Reduce resource usage

  1. Eliminate slow PHP code. Slow PHP scripts increase memory usage by increasing the number of concurrently running PHP processes. When code is slow, a larger number of concurrently running PHP processes are required to serve the same number of requests.
  2. Disable any WordPress plugins you don’t need. High CPU and memory usage is often the result of poorly-written or resource-intensive WordPress plugins.
  3. Check the server’s MySQL slow query log. Many PHP scripts spend most of their time waiting for responses to SQL queries. If SQL queries are slow, PHP requests take longer to complete which increases the number of running PHP processes and so increases memory usage.
  4. Use the newest version of PHP an app supports. In general, newer PHP versions use less CPU and memory than older PHP versions.
  5. Use caching. Use forms of caching that serve requests from static files such as with the WordPress Cache Enabler plugin.