Optimizing PHP Application Performance: Tips and Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction

PHP application performance is one of the key success factors for any web project. A slow website not only drives users away but also negatively impacts SEO rankings. In this article, we will cover the main methods for optimizing PHP code and server infrastructure that will help speed up your application.

Optimization is not a one-time action but an ongoing process. Let's start with the most effective techniques that provide the greatest performance boost.



1. Data Caching

Caching is one of the most powerful tools for speeding up PHP applications. Instead of generating a response from scratch every time, you can save the result and serve it from the cache.



1.1. In-Memory Caching (Redis/Memcached)

Use in-memory caching systems such as Redis or Memcached. They are ideal for storing results of complex queries, sessions, and frequently requested data.

<?php// Example of using Redis for caching$redis = new Redis();$redis->connect('127.0.0.1', 6379);

$cacheKey = 'user_profile_' . $userId;$profile = $redis->get($cacheKey);

if ($profile === false) { // Data not in cache — execute heavy query $profile = getUserProfileFromDatabase($userId); $redis->setex($cacheKey, 3600, serialize($profile)); // Cache for 1 hour}

$profile = unserialize($profile);?>


1.2. HTML Output Caching (Full Page Cache)

For static pages or pages that rarely change, use caching of the ready HTML. This can be implemented using Varnish or built-in caching in popular frameworks (e.g., Symfony HTTP Cache).



2. Database Optimization

The database often becomes a bottleneck. Optimizing queries and database structure can provide a significant speed boost.



2.1. Use Indexes

Ensure that all columns involved in WHERE, JOIN, and ORDER BY conditions have indexes. This speeds up search by tens of times.



2.2. Query Optimization with EXPLAIN

Before executing a complex query, use the EXPLAIN command to understand how MySQL executes it. Look for "Using filesort" or "Using temporary" — these are signs of a non-optimal query.

<?php// Bad: N+1 queries$users = $db->query("SELECT * FROM users");foreach ($users as $user) {    $posts = $db->query("SELECT * FROM posts WHERE user_id = " . $user['id']);    // ...}

// Good: single query with JOIN$users = $db->query(" SELECT u.*, p.title as post_title FROM users u LEFT JOIN posts p ON p.user_id = u.id");?>


2.3. Pagination Instead of LIMIT with Large Offset

Using LIMIT with a large OFFSET forces the database to scan many rows. Use cursor-based pagination (WHERE id > last_id).

<?php// Bad: LIMIT 100000, 20$stmt = $db->query("SELECT * FROM articles ORDER BY id LIMIT 100000, 20");

// Good: cursor-based pagination$lastId = $_GET['last_id'] ?? 0;$stmt = $db->query("SELECT * FROM articles WHERE id > $lastId ORDER BY id LIMIT 20");?>


3. Using OPcache and Class Autoloading

PHP is an interpreted language, and each request requires script compilation. OPcache solves this problem by storing compiled code in memory.



3.1. Configuring OPcache

Ensure OPcache is enabled and configured correctly. Here are the optimal parameters for most projects:

; php.iniopcache.enable=1opcache.memory_consumption=128opcache.interned_strings_buffer=8opcache.max_accelerated_files=10000opcache.revalidate_freq=2opcache.fast_shutdown=1


3.2. Proper Class Autoloading

Use Composer for class autoloading. This allows loading only those classes that are

Blogs

Book Recommendations