note 37533 added to function.array-search

From: Date: Tue, 18 Nov 2003 23:59:27 +0000
Subject: note 37533 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-60599@lists.php.net to get a copy of this message
Searching arrays is a very slow process. I've tried to use as many strings as I can for where an array is called, if possible. Here's a quick test to show the (eye-popping) difference between searching for a match between strings and arrays: <?php $test_string = ''; for ($i=1; $i <= 500000; $i++) { $test_string .= '['.$i.']'; } $test_array = array(); for ($i=1; $i <= 5000; $i++) { $test_array[] = $i; } $time_str = getmicrotime(); for ($i=1; $i <= 500000; $i++) { strstr($i,$test_string); } $time_str = getmicrotime() - $time_str; $time_array = getmicrotime(); for ($i=1; $i <= 5000; $i++) { array_search($i,$test_array); } $time_array = getmicrotime() - $time_array; echo "<H1>Test Results</H1>\r\n"; echo "<P>String Test:&nbsp; $time_str seconds.</P>\r\n"; echo "<P>Array Test:&nbsp; $time_array seconds.</P>\r\n"; function getmicrotime(){ list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } ?> This code block takes some time to get going (because of the number of strings to place into memory), the results, even on modest hardware are staggering. Comparing 500000 strstr() operations to 5000 array_search() operations on a P3-800 with 512 MB of RAM got the following output: [H1]Test Results[/H1] [P]String Test: 3.09137701988 seconds.[/P] [P]Array Test: 4.23609495163 seconds.[/P] The getmicrotime() function came from the note on microtime(), so that's not mine...credit to "daniel141 at yahoo dot com". STRINGS RULE! -- Justin White YTZ Technical Services, LLC ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37533 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37533&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37533&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#60599) next »