note 129889 added to function.in-array
| From: | eurorusty@yahoo.ca | Date: | Wed, 27 Nov 2024 18:23:51 +0000 |
| Subject: | note 129889 added to function.in-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221690@lists.php.net to get a copy of this message | ||
I'm not sure why PHP doesn't provide a way to specify a binary search. Here's an
example of the performance gains, for this array size, about 50x improvement using interpreted PHP.
If built in, it could probably achieve around 1000x improvement, again for this array size.
<?php
// Set up sorted array
$X = array(1);
for ($j = 1; $j < 50000; ++$j)
$X[] = $X[$j - 1] + rand(1, 6);
// Using in_array
$x = -microtime(true);
$m = 0;
for ($j = 0; $j < 10000; ++$j)
$m += in_array(rand(1, 175000), $X);
$x += microtime(true);
echo $x.PHP_EOL;
// Using binarySearch
$x = -microtime(true);
$m = 0;
for ($j = 0; $j < 10000; ++$j)
$m += binarySearch($X, rand(1, 175000));
$x += microtime(true);
echo $x.PHP_EOL;
function binarySearch($array, $value) {
$low = 0;
$high = count($array) - 1;
while ($low <= $high) {
$pivot = floor(($low + $high) / 2);
if ($array[$pivot] == $value)
return true;
if ($value < $array[$pivot])
$high = $pivot - 1;
else
$low = $pivot + 1;
}
// No match
return false;
}
/* Sample outputs, first is in_array, second is binarySearch
1.3544600009918
0.026464939117432
1.6158990859985
0.033976078033447
1.5184400081635
0.026461124420166
*/
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.84.18 (proxied: 207.107.149.164)
----
Manual Page -- https://php.net/manual/en/function.in-array.php
Edit -- https://main.php.net/note/edit/129889
Del: integrated -- https://main.php.net/note/delete/129889/integrated
Del: useless -- https://main.php.net/note/delete/129889/useless
Del: bad code -- https://main.php.net/note/delete/129889/bad+code
Del: spam -- https://main.php.net/note/delete/129889/spam
Del: non-english -- https://main.php.net/note/delete/129889/non-english
Del: in docs -- https://main.php.net/note/delete/129889/in+docs
Del: other reasons-- https://main.php.net/note/delete/129889
Reject -- https://main.php.net/note/reject/129889
Search -- https://main.php.net/manage/user-notes.php