Wednesday, November 7, 2012

PHP Accessing array performance test / benchmark

Hi, All
Today we are going to benchmark array access, the key stored in variable, double quoted and single. Let we go, as usual, we go short and simple! As usual we run 1 million times.

Test Stand:
Hardware:
Intel i7 860 @ 2.8Ghz
Asus P7H55-M PRO
8GB DDR @ 1600Mhz Timings 8-8-8-24
SSD 80GB Intel SA2M080

Software
Windows 7 x64
Apache 2.2.17 (x86)
PHP 5.3.5

Let's begin.

Our test script looks such simple as:
set_time_limit(0);
$time_start = microtime(true);

$arr = array('name'=>'vasya', 'last_name'=>'patrik');
$tmp = NULL;
$i = 0;
while($i < 1000000){
    $tmp = NULL;
    $tmp = $arr["name"]; // different access method
    ++$i;
}
echo number_format(microtime(true)-$time_start, 6, '.', '').' seconds';

First we will run with double quotes. We will use $tmp = $arr["name"].
The results will be quiet interesting, and, as usual we calculate avg time for 10 runs.
First Case: $tmp = $arr["name"]
Result: 0.1790sec.

Second Case: $tmp = $arr['name']
Result: 0.1763sec.

Third Case: $tmp = $arr[$key]
Result: 0.1832sec.

Fourth Case: $tmp = $arr[0](after array refined to use int keys)
Result: 0.1659sec.

PHP Accessing array alternatives benchmark / performance test conclusion:
By the test results you can see that accessing array almost doesn't make sens from performance point of view, as we can see for 1 million assignments of $arr[key] to $tmp the coded runes very quick, 0.16-0.18s. Although makes sens, the fastest way of accessing is by integer key, as not surprisingly accessing array with a key stored in variable the slowest way. Just remember to use int keys whenever is possible, as this way will speed up the execution time of the code.

Sincerely,
Ruskevych Valentin

No comments: