Benchmarking PHP code

Josh Sherman
3 min read
Software Development PHP

Have you ever asked yourself, “I wonder which of these blocks of code will run faster?” I know I have and I use a very basic template for setting up these benchmarking experiments. The gist of the script is to run through each block of code n times tracking the amount of time and memory it took to run. It’s not nearly as complete as it could be, but it serves as a good enough starting point for doing some quick tests.

<?php

$n = 1000000;

$start_time = microtime(true);
$start_mem  = memory_get_usage(true);

for ($i = 0; $i < $n; $i++)
{

}

$time = microtime(true) - $start_time;
$mem  = memory_get_usage(true) - $start_mem;

echo "Test 1\t{$time}\t{$mem}\n";

You can duplicate the test block as many times as you need it. Here’s a working benchmark I wrote to see if PHP’s built-in array_keys function was actually faster than doing a foreach:

<?php

$n = 1000000;

$array = [
    'one'   => 'This is the first',
    'two'   => 'This is the second',
    'three' => 'This is the third',
    'four'  => 'This is the fourth',
    'five'  => 'This is the fifth',
];

$start_time = microtime(true);
$start_mem  = memory_get_usage(true);

for ($i = 0; $i < $n; $i++)
{
    unset($array_keys);
    $array_keys = array_keys($array);
}

$time = microtime(true) - $start_time;
$mem  = memory_get_usage(true) - $start_mem;

echo "array_keys()\t{$time}\t{$mem}\n";

$start_time = microtime(true);
$start_mem  = memory_get_usage(true);

for ($i = 0; $i < $n; $i++)
{
    unset($array_keys);

    foreach ($array as $key => $value)
    {
        $array_keys[] = $key;
    }
}

$time = microtime(true) - $start_time;
$mem  = memory_get_usage(true) - $start_mem;

echo "foreach()\t{$time}\t{$mem}\n";

One improvement would be to track the average time per iteration as well as the fastest and slowest iteration. I went ahead and threw the code in a GitHub gist in case anyone wants to fork and improve upon it.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Grinding It Out: The Making of McDonald's

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles