Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bwg
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bwg/14a06d3ba51675e514f1 to your computer and use it in GitHub Desktop.
Save bwg/14a06d3ba51675e514f1 to your computer and use it in GitHub Desktop.
array_key_exists vs. isset
<?php
$iterations = 100000;
$value = [
'one' => 1,
'two' => 2,
'three' => 3,
];
$totals = [
'isset_true' => 0,
'isset_false' => 0,
'array_key_true' => 0,
'array_key_false' => 0,
];
echo "PHP Version ".phpversion()."\n\n";
echo str_repeat('-', 50)."\n";
//-----------------------------------------------------------------------------
echo "Testing isset over ".number_format($iterations)." iterations:\n\n";
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
if (isset($value['one'])) {}
}
$end = microtime(true);
$duration = ($end - $start) * 1000;
$totals['isset_true'] += $duration;
echo str_pad('isset true', 35)."{$duration}\n";
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
if (isset($value['fail'])) {}
}
$end = microtime(true);
$duration = ($end - $start) * 1000;
$totals['isset_false'] += $duration;
echo str_pad('isset false', 35)."{$duration}\n\n";
//-----------------------------------------------------------------------------
echo "Testing array_key_exists over ".number_format($iterations)." iterations:\n\n";
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
if (array_key_exists('one', $value)) {}
}
$end = microtime(true);
$duration = ($end - $start) * 1000;
$totals['array_key_true'] += $duration;
echo str_pad('array_key_exists true', 35)."{$duration}\n";
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
if (array_key_exists('fail', $value)) {}
}
$end = microtime(true);
$duration = ($end - $start) * 1000;
$totals['array_key_false'] += $duration;
echo str_pad('array_key_exists false', 35)."{$duration}\n";
//-----------------------------------------------------------------------------
echo "\n".str_repeat('-', 50)."\n";
echo str_pad('', 35);
echo str_pad('total (ms)', 20)."\n";
echo str_repeat('-', 50)."\n";
foreach ($totals as $name => $total) {
echo str_pad($name, 35);
echo str_pad($total, 20)."\n";
}
echo "\n";
PHP Version 5.6.3
--------------------------------------------------
Testing isset over 100,000 iterations:
isset true 23.11897277832
isset false 21.745920181274
Testing array_key_exists over 100,000 iterations:
array_key_exists true 95.006942749023
array_key_exists false 88.358879089355
--------------------------------------------------
total (ms)
--------------------------------------------------
isset_true 23.11897277832
isset_false 21.745920181274
array_key_true 95.006942749023
array_key_false 88.358879089355
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment