Recently during a casual conversation someone asked me what would be the fastest way to check for array presence in PHP. Normally you don’t tend to think of the empty array as anything special, but they do occur a lot – a query from the database can return 0 rows, the object that has been in cache has expired, or the Web page has 0 inbound links pointing to it. Pretty usual way to go about it i to use count or its twin brother sizeof to find out the length of the array and behave accordingly depending on whether the if statement returns true or not.
It was pointed out to me, however, that both count and sizeof always need to conduct the pointer arithmetics, even if the array in question is of zero size. Checking for the existence of the first element of the array, however, would involve no pointer arithmetics, since referencing $array[0] is the same as referencing $array pointer. But how much faster is it? I set out to test it with a pretty simple script that would run both comparisons a million times. Since accessing the first element of an empty array would generate a PHP notice (note that it’s not an error, the pointer is still valid), I had to revert to error_reporting(0) at the beginning of the file to exclude the time spent on printing out PHP notices.
It’s also useful to know that whenever the if statement contains a clause that doesn’t have executable code, it will be optimized by the interpreter, and therefore something should be done inside the if() clause once we’re there. So how about running a counter from 1 to a million, checking for the same array over and over, and printing the counter value on each run?
error_reporting(0);
$array1 = array();
$time1 = time();
for ($x=0; $x<1000000; $x++)
{
if (count($array1)==0)
{echo $x;
}
}
$time2 = time();
for ($x=0; $x<1000000;$x++)
{
if(!$array1[0])
{echo $x;
}
}
$time3 = time();
echo ($time2-$time1)."\n";
echo ($time3-$time2)."\n";
The results?
99937
36
More than 2,500x difference.
