Skip to content

Instantly share code, notes, and snippets.

@kanduvisla
Created July 10, 2018 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanduvisla/f8d50bbded11068271c7e2baefaab6a5 to your computer and use it in GitHub Desktop.
Save kanduvisla/f8d50bbded11068271c7e2baefaab6a5 to your computer and use it in GitHub Desktop.
PHP Performance test for isset() vs array_key_exists() vs coalesce operator
<?php
$iterations = 1000000;
$arr = ['foo' => 'bar'];
function testIsset()
{
global $iterations, $arr;
$startTime = microtime(true);
for ($i = 0; $i < $iterations; $i += 1) {
$val1 = isset($arr['foo']) ? $arr['foo'] : 'baz';
$val2 = isset($arr['boo']) ? $arr['boo'] : 'qux';
}
$endTime = microtime(true);
$elapsedTime = $endTime - $startTime;
echo "isset(): {$elapsedTime} seconds\n";
}
function testArrayKeyExists()
{
global $iterations, $arr;
$startTime = microtime(true);
for ($i = 0; $i < $iterations; $i += 1) {
$val1 = array_key_exists('foo', $arr) ? $arr['foo'] : 'baz';
$val2 = array_key_exists('boo', $arr) ? $arr['boo'] : 'qux';
}
$endTime = microtime(true);
$elapsedTime = $endTime - $startTime;
echo "array_key_exists(): {$elapsedTime} seconds\n";
}
function testCoalesce()
{
global $iterations, $arr;
$startTime = microtime(true);
for ($i = 0; $i < $iterations; $i += 1) {
$val1 = $arr['foo'] ?? 'baz';
$val2 = $arr['boo'] ?? 'qux';
}
$endTime = microtime(true);
$elapsedTime = $endTime - $startTime;
echo "coalesce: {$elapsedTime} seconds\n";
}
echo "{$iterations} iterations:\n";
testIsset();
testArrayKeyExists();
testCoalesce();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment