Skip to content

Instantly share code, notes, and snippets.

@RobinDev
Created November 21, 2022 11:01
Show Gist options
  • Save RobinDev/b909b960ad4d3cbad798c0ac5cf595d7 to your computer and use it in GitHub Desktop.
Save RobinDev/b909b960ad4d3cbad798c0ac5cf595d7 to your computer and use it in GitHub Desktop.
Fastest way to fin if a key exists in an array with PHP 8
array(4) {
  'array_key_exists' =>
  double(0.76186203956604)
  'isset' =>
  double(0.78142905235291)
  'noCheck' =>
  double(0.80179715156555)
  'empty' =>
  double(0.80491018295288)
}

Null coallescent is not the better solution...

<?php
$a = [];
$result = [];
for($i=0;$i<20000000;$i++)
$a[sha1($i)] = sha1($i);
$numIterations = 10000000;
echo 'start test '.chr(10);
$start = microtime(true);
for ($i = 0; $i < $numIterations; $i++) { $a['none'] ?? ''; };
$result['noCheck'] = microtime(true) - $start;
echo '2nd test '.chr(10);
$start = microtime(true);
for ($i = 0; $i < $numIterations; $i++) { empty($a['none']) ? '' : ''; };
$result['empty'] = microtime(true) - $start;
echo '3rd test '.chr(10);
$start = microtime(true);
for ($i = 0; $i < $numIterations; $i++) { isset($a['none']) ? '' : ''; };
$result['isset'] = microtime(true) - $start;
echo '4th test '.chr(10);
$start = microtime(true);
for ($i = 0; $i < $numIterations; $i++) { array_key_exists('none', $a) ? '' : ''; };
$result['array_key_exists'] = microtime(true) - $start;
asort($result);
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment