note 82867 deleted from function.array-key-exists by crell
| From: | crell@php.net | Date: | Wed, 29 Jun 2022 20:44:52 +0000 |
| Subject: | note 82867 deleted from function.array-key-exists by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218768@lists.php.net to get a copy of this message | ||
Note Submitter: tmont
----
The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a
little benchmark to see which is faster:
<?php
// one-dimensional arrays
$array = array_fill(0,50000,'tommy is the best!');
$arraykeyexists_result = array();
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
if (array_key_exists($i,$array)) {
$arraykeyexists_result[] = 1;
}
else {
$arraykeyexists_result[] = 0;
}
}
$arrtime = round(microtime(true)-$start,3);
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
if (isset($array[$i])) {
$arraykeyexists_result[] = 1;
}
else {
$arraykeyexists_result[] = 0;
}
}
$istime = round(microtime(true)-$start,3);
$totaltime = $arrtime+$istime;
$arrpercentage = round(100*$arrtime/$totaltime,3);
$ispercentage = round(100*$istime/$totaltime,3);
echo "array_key_exists(): $arrtime [$arrpercentage%] seconds\n";
echo "isset(): $istime [$ispercentage%] seconds\n";
?>
On Windows, the output is similar to
array_key_exists(): 0.504 [82.895%] seconds
isset(): 0.104 [17.105%] seconds
On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.