note 51799 deleted from function.array-key-exists by bjori

From: Date: Mon, 01 May 2006 22:29:07 +0000
Subject: note 51799 deleted from function.array-key-exists by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-110306@lists.php.net to get a copy of this message
Note Submitter: dave underscore bachtel ... again ---- It appears that ($somearr[testindex]=== NULL) is comperable to isset() for speed (both of which are EXTREMELY faster than array_key_exists()). Here is some code that I used for the comparisons. <?php //Example Code: for(some_loop_here with an increasingly larger array being searched) { benchMarkThis("arraykeyexists",1); $foo = array_key_exists($newfriend,$list); benchMarkThis("arraykeyexists"); benchMarkThis("eqeqeqnull",1); $foo = ($list[$newfriend] === NULL); benchMarkThis("eqeqeqnull"); benchMarkThis("isset",1); $foo = isset($list[$newfriend]); benchMarkThis("isset"); } //this function was taken from example code on php.net for the microtime function // return the time in seconds function getmicrotime(){ list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } //Takes in the name of a specific benchmark to track, reset parameter is an optional reset back to 0 function benchMarkThis($bmname, $reset=0) { static $lastTime = array(); static $totalTime = array(); if ($reset == 1) //reset the clock back to 0 { $lastTime[$bmname] = getmicrotime(); return; } $now = getmicrotime(); $diff = $now - $lastTime[$bmname]; $diff = round($diff, 6); $totalTime[$bmname] += $diff; echo "$bmname time=$diff, elapsed=$totalTime[$bmname]<br>"; $lastTime[$bname] = $now; } ?> Ouput (last iteration): eqeqeqnull time=0.000126, elapsed=0.993481 isset time=0.000119, elapsed=0.768909 arraykeyexists time=0.011609, elapsed=52.58483 Moral of the story: if you can get away with it, do NOT use array_key_exists().

« previous php.notes (#110306) next »