note 60559 deleted from function.in-array by danbrown

From: Date: Mon, 08 Jun 2009 21:44:43 +0000
Subject: note 60559 deleted from function.in-array by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-156516@lists.php.net to get a copy of this message
Note Submitter: SBoisvert at Bryxal dot ca ---- Many comments have pointed out the lack of speed of in_array (with a large set of items [over 200 and you'll start noticing) the algorithm is (O)n. You can achieve an immense boost of speed on changin what you are doing. lets say you have an array of numerical Ids and have a mysql query that returns ids and want to see if they are in the array. Do not use the in array function for this you could easily do this instead. if (isset($arrayOfIds[$Row['Id'])) to get your answer now the only thing for this to work is instead of creating an array like such $arrayOfIds[] = $intfoo; $arrayOfIds[] = $intfoo2; you would do this: $arrayOfIds[$intfoo] = $intfoo; $arrayOfIds[$intfoo2] = $intfoo2; The technical reason for this is array keys are mapped in a hash table inside php. wich means you'll get O(1) speed. The non technical explanation is before is you had 100 items and it took you 100 microseconds for in_array with 10 000 items it would take you 10 000 microseconds. while with the second one it would still take you 100 microsecond if you have 100 , 10 000 or 1 000 000 ids. (the 100 microsecond is just a number pulled out of thin air used to compare and not an actual time it may take)

« previous php.notes (#156516) next »