note 51799 added to function.array-key-exists

From: Date: Mon, 11 Apr 2005 17:19:13 +0000
Subject: note 51799 added to function.array-key-exists
Groups: php.notes 
Request: Send a blank email to php-notes+get-87850@lists.php.net to get a copy of this message
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(). ---- Manual Page -- http://www.php.net/manual/en/function.array-key-exists.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+51799 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51799&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51799&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51799&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51799&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51799&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+51799&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#87850) next »