benchmark: array_key_exists vs isset

When the aim is to check if the element exists in an array and has a value not null, better to use isset(array[index]), that is much faster than array_key_exists(index, array).

#PHP 5.3.0 command line – Amd turion 64 1.6 Ghz

#create array
$a = array();
for(
$i = 0; $i<100000; $i++) {
$a[] = $i asd a”.($i*2).” sd”;
}

#isset
$t = microtime(true);
for(
$i = 0; $i<10000000; $i++) {
isset(
$a[$i]);
}
print
microtime(true)-$t; //4.16 sec

#array_key_exists
$t = microtime(true);
for(
$i = 0; $i<10000000; $i++) {
array_key_exists($i, $a);
}
print
microtime(true)-$t; //11.7 sec




note: array_key_exists(index, array)and isset(array[index]) are a little different:

$a = array(0=>0, 1=>NULL);
print isset(
$a[1])?1:0; //0
print array_key_exists(1, $a)?1:0; //1

note: eAccelerator ( and probably also other PHP accelerators) don’t improve the array access time

note: xDebug (and probably zend optimizer) activated can slow down a lot the performance (by 6/7 times) with huge arrays like these !