note 60559 added to function.in-array
| From: | SBoisvertatBryxaldotca at osu1 dot php dot net | Date: | Wed, 11 Jan 2006 03:18:53 +0000 |
| Subject: | note 60559 added to function.in-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-101527@lists.php.net to get a copy of this message | ||
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)
----
Manual Page -- http://www.php.net/manual/en/function.in-array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+60559
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60559&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60559&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60559&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60559&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60559&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60559&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60559&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+60559&report=yes
Search -- http://master.php.net/manage/user-notes.php