26Feb/100
PHP Array Performance
Index Checking
The functional difference between array_key_exists($key, $array) and isset($array[$key]) is that isset returns false when the key exists but contains null. Functionality aside, there is a demonstrable performance difference.
$dataSet = array(); $size = 0x1FFFF; $i = $size; while ($i--) $dataSet[$i] = $i+1; $start = microtime(true); $i = $size; while ($i--) array_key_exists($i, $dataSet); //isset($dataSet[$i]); echo "Time: ". (microtime(true) - $start);
Sure enough, after averaging a few benchmarks together the outcome was clear.
- isset
- 0.0248870849609
- array_key_exists
- 0.604112148285
When performance is important target isset() when applicable. It's even possible to use a fall through to increase performance, here's an example from my Options class: if (!isset($this->_options[$resolvedName]) && !array_key_exists($resolvedName, $this->_options))
Append Performance
In the following test case there was no performance difference between usage of append or directly addressing an index.
$dataSet = array(); $size = 0x1FFFF; $i = $size; $start = microtime(true); while ($i--) $dataSet[] = $i+1; //$dataSet[$i] = $i+1; echo "Time: ". (microtime(true) - $start);