Image created with Canva

Tips to Make Your PHP Script Run Faster

Serghei Pogor
7 min readApr 5, 2024

--

Let’s dive in, keep it simple, and add a sprinkle of fun along the way. 🚀

The Magic of Caching 🧙‍♂️

First off, let’s chat about caching. Think of caching like storing your toys in a toy box. Instead of searching your whole house for your favorite action figure, you know it’s in the box. Similarly, caching saves pieces of your code or data so your script doesn’t have to go look for it every time. It just grabs it from the cache! Super fast, right?

Here’s a simple way to use file caching in PHP:

$cacheFile = 'cache.txt';
if (file_exists($cacheFile)) {
$content = file_get_contents($cacheFile);
echo "From cache: " . $content;
} else {
$content = "This is some heavy data, like from a database.";
file_put_contents($cacheFile, $content);
echo "From source: " . $content;
}

In this example, we check if our cache file exists. If it does, we use it. If not, we create it. Easy-peasy!

The Power of OpCache 🚀

OpCache is a powerful tool that compiles your PHP scripts into code that your computer understands more quickly. It’s like teaching your computer to understand your PHP code as if it was its native language. Here’s the thing: it’s usually enabled on servers but might be off on your localhost.

To turn on OpCache with PHP, add these lines to your php.ini file:

opcache.enable=1
opcache.revalidate_freq=0
opcache.validate_timestamps=1
opcache.max_accelerated_files=10000
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.fast_shutdown=1

Remember to restart your local server after making these changes!

Database Queries Optimization 📊

Now, let’s talk about talking to databases. You want to ask your database questions (queries) in the smartest way possible. Instead of asking your database the same question over and over, ask once and remember the answer. This is called query optimization.

Here’s a before and after using PHP’s PDO for better database interaction:

Before Optimization:

// This is slow because it asks the same question too many times.
foreach ($userIds as $userId) {
$query = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$query->execute([$userId]);
$users[] = $query->fetch();
}

After Optimization:

// Ask once, get all the answers - much faster!
$placeholders = implode(',', array_fill(0, count($userIds), '?'));
$query = $pdo->prepare('SELECT * FROM users WHERE id IN (' . $placeholders . ')');
$query->execute($userIds);
$users = $query->fetchAll();

See the difference? We went from asking for each user individually to asking for all at once!

By using caching, enabling OpCache, and optimizing database queries, you’re on your way to making your PHP scripts run like the wind.

Identifying Bottlenecks: Where’s the Slowness?

Before we can optimize our PHP scripts, we need to pinpoint the areas that are slowing us down. It could be inefficient loops, redundant function calls, or bloated code structures. Let’s roll up our sleeves and dive into the code to uncover these bottlenecks!

Optimization Techniques: Making Every Line Count

Now, let’s unleash some optimization sorcery on our PHP code to make it run like a well-oiled machine. Here are some tried-and-tested techniques to optimize your PHP scripts:

1. Minimize Function Calls:

Instead of calling a function multiple times within a loop, consider storing the result in a variable and reusing it. Let’s see this in action:

<?php
// Inefficient
for ($i = 0; $i < 1000; $i++) {
$result = calculateSomething(); // Function call within loop
// Do something with $result
}

// Optimized
$result = calculateSomething(); // Call function once
for ($i = 0; $i < 1000; $i++) {
// Do something with $result
}

By minimizing function calls inside loops, we reduce overhead and improve performance.

2. Use Built-in Functions:

PHP provides a plethora of built-in functions optimized for performance. Instead of reinventing the wheel, leverage these functions wherever possible. For example:

<?php
// Inefficient
$result = array();
foreach ($array as $item) {
$result[] = doSomething($item);
}

// Optimized
$result = array_map('doSomething', $array);

The array_map() function is optimized for iterating over arrays, resulting in cleaner and faster code.

3. Embrace PHP’s Type System:

PHP’s dynamic typing can be both a blessing and a curse. By enforcing strict typing and using appropriate data types, we can improve code clarity and performance. Let’s see an example:

<?php
// Inefficient
$total = 0;
foreach ($prices as $price) {
$total += $price;
}

// Optimized
$total = array_sum($prices);

The array_sum() function is optimized for summing array values, resulting in faster execution.

Understanding Asynchronous PHP: What’s the Fuss About?

But first, what exactly is asynchronous PHP, and why should you care? 🤔 In traditional PHP, each request is handled synchronously, meaning one request must complete before the next one begins. Asynchronous PHP breaks free from this limitation, allowing multiple tasks to be executed concurrently, resulting in significantly faster performance and improved scalability.

The Awaited Solution: Amp Up Your PHP with Async Await

Now, let’s roll up our sleeves and dive into the code to see asynchronous PHP in action! We’ll be using the popular Amp library to harness the power of async await. Buckle up, because things are about to get wild!

1. Installing Amp:

First things first, let’s install the amphp/amp package via Composer:

composer require amphp/amp

2. Writing Asynchronous Code:

Now, let’s write some asynchronous PHP code to fetch data from multiple URLs concurrently:

<?php
require 'vendor/autoload.php';

use Amp\Loop;
use Amp\Http\Client\{HttpClient, HttpClientBuilder};

Loop::run(function () {
$urls = ['https://example.com/1', 'https://example.com/2', 'https://example.com/3'];

$httpClient = HttpClientBuilder::buildDefault();
$promises = [];

foreach ($urls as $url) {
$promises[$url] = $httpClient->request($url);
}

$responses = yield $promises;

foreach ($responses as $url => $response) {
printf("Response from %s: %s\n", $url, yield $response->getBody()->buffer());
}
});

Here, we’re fetching data from multiple URLs concurrently using Amp’s asynchronous HTTP client.

3. Embrace the Power of Parallel Processing:

By embracing asynchronous PHP, we can perform tasks in parallel, unlocking a whole new level of performance and scalability. Whether it’s fetching data from multiple APIs, processing large datasets, or handling concurrent connections, asynchronous PHP has got you covered!

Unleashing the Power of Distributed Computing for PHP

What exactly is distributed computing, and why should you care?

🤔 In a nutshell, distributed computing involves breaking down complex tasks into smaller subtasks and distributing them across multiple machines or nodes. This allows for parallel execution of tasks, resulting in faster performance, improved fault tolerance, and enhanced scalability.

The Distributed Dream: PHP and Apache Kafka

Now, let’s dive into the code to see distributed computing in action! We’ll be leveraging Apache Kafka — a distributed streaming platform — to demonstrate how PHP can seamlessly integrate with distributed systems.

1. Setting Up Apache Kafka:

First things first, let’s set up Apache Kafka on our local machine or a remote server. You can follow the official documentation for installation instructions.

2. Producing Messages with PHP:

Next, let’s write some PHP code to produce messages to a Kafka topic:

<?php
require 'vendor/autoload.php';

use RdKafka\Producer;
use RdKafka\Conf;

$conf = new Conf();
$conf->set('bootstrap.servers', 'localhost:9092');

$producer = new Producer($conf);
$producer->addBrokers('localhost:9092');

$topic = $producer->newTopic('test');

for ($i = 0; $i < 10; $i++) {
$message = 'Message ' . $i;
$producer->produce(RD_KAFKA_PARTITION_UA, 0, $message);
}

$producer->flush(10000);

Here, we’re using the rdkafka extension to produce messages to a Kafka topic named "test".

3. Consuming Messages with PHP:

Now, let’s write another PHP script to consume messages from the Kafka topic:

<?php
require 'vendor/autoload.php';

use RdKafka\Consumer;
use RdKafka\ConsumerTopic;
use RdKafka\Message;

$conf = new RdKafka\Conf();
$conf->set('group.id', 'test-consumer-group');
$conf->set('metadata.broker.list', 'localhost:9092');

$consumer = new Consumer($conf);
$consumerTopic = $consumer->newTopic('test');

$consumerTopic->consumeStart(0, RD_KAFKA_OFFSET_BEGINNING);

while (true) {
$message = $consumerTopic->consume(0, 1000);
if ($message->err) {
echo "Error: {$message->errstr()}\n";
} else {
echo "Received message: {$message->payload}\n";
}
}

This script consumes messages from the “test” topic and echoes them to the console.

4. Embrace the Power of Distributed Computing:

By embracing distributed computing with PHP and Apache Kafka, we can unlock unparalleled scalability and performance for our applications. Whether it’s processing massive streams of data, orchestrating complex workflows, or building real-time analytics pipelines, the possibilities are endless!

Boosting PHP Performance with Profiling and Optimization

Ahoy, PHP enthusiasts! 🚀 Welcome to the final leg of our voyage to optimize PHP scripts for localhost. In this pivotal part, we’re delving deep into the world of profiling and optimization, armed with the tools and techniques to supercharge our code for maximum performance.

Unlocking the Power of Profiling: Identifying Performance Bottlenecks

Before we can optimize our PHP scripts, we need to identify the areas that are slowing us down. That’s where profiling comes into play. Profiling tools like Xdebug and Blackfire enable us to analyze the execution of our PHP code in detail, revealing which functions, loops, or database queries are consuming the most time.

Using Xdebug for Profiling:

Xdebug is a powerful tool for profiling PHP scripts. To start profiling with Xdebug, follow these simple steps:

  1. Install Xdebug extension for PHP.
  2. Enable profiling in your php.ini configuration file.
  3. Add profiling commands to your PHP script:
<?php

// Start profiling
xdebug_start_profiling();

// Your PHP code here
xdebug_stop_profiling();

Once profiling is enabled, Xdebug will generate a profiling report containing detailed information about the execution time of each function and line of code.

🔔 Click Subscribe to catch more coding fun.
👏🏻 Love it? Give a big clap.
💬 Got a cool idea or funny coding joke? Drop it in the comments.

Share these tips with your fellow developers to help each other succeed together.

Thanks for hanging out and reading. You rock! 🚀

Hold on a sec!!! Want more of my fun stuff in your inbox? Sign up here! 📩

--

--