Array key lookup: isset() or array_key_exists() or @ ?

Lessons learned:
  • isset() is faster than array_key_exists()
  • array_key_exists() is faster than @
  • @ is slower than ignoring notices with error_reporting()

Here is the code running on a 1.4 GHz machine with PHP 5.4.0:

error_reporting(E_ALL & ~E_NOTICE);

$a = array();
for ($i=0; $i<100000; $i++) $a[] = $i*2;

$start = microtime(true);
for ($i=0; $i<100000; $i++) if (isset($a[$i])) {}
echo ' '.(microtime(true)-$start); // 0.017

$start = microtime(true);
for ($i=0; $i<100000; $i++) if (array_key_exists($i, $a)) {}
echo ' '.(microtime(true)-$start); // 0.064

$start = microtime(true);
for ($i=0; $i<100000; $i++) if (@$a[$i]) {}
echo ' '.(microtime(true)-$start); // 0.095

$start = microtime(true);
for ($i=0; $i<100000; $i++) if ($a[$i]) {}
echo ' '.(microtime(true)-$start); // 0.016

$a = array();

$start = microtime(true);
for ($i=0; $i<100000; $i++) if (isset($a[$i])) {}
echo ' '.(microtime(true)-$start); // 0.016

$start = microtime(true);
for ($i=0; $i<100000; $i++) if (array_key_exists($i, $a)) {}
echo ' '.(microtime(true)-$start); // 0.058

$start = microtime(true);
for ($i=0; $i<100000; $i++) if (@$a[$i]) {}
echo ' '.(microtime(true)-$start); // 0.29

$start = microtime(true);
for ($i=0; $i<100000; $i++) if ($a[$i]) {}
echo ' '.(microtime(true)-$start); // 0.20

Comments

Popular posts from this blog

How to show only month and year fields in android Date-picker?

How to construct a B+ tree with example

Conflict Serializability in database