Created
June 10, 2019 20:03
-
-
Save cereal-s/1427a52f88bbedafe3a06a55a671015b to your computer and use it in GitHub Desktop.
Find value into an array. Comparison between for loop + if/else, in_array(), and array_flip() + for loop + isset().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function _report($start) { | |
$total_time = microtime( true ) - $start; | |
echo PHP_EOL; | |
echo 'Total time: ' . number_format($total_time, 6); | |
echo PHP_EOL; | |
echo PHP_EOL; | |
} | |
$a = []; | |
for ($i = 0; $i < 1000000; $i++) { | |
$a[] = mt_rand(1, 10000000); | |
} | |
$c = $b = $a; | |
// Randomize | |
shuffle($b); // random number | |
shuffle($c); // collection to search | |
$rnd = $b[0]; | |
$cnt = count($a); | |
echo 'Size: ' . $cnt; | |
echo PHP_EOL; | |
echo 'Random: ' . $rnd; | |
echo PHP_EOL; | |
echo PHP_EOL; | |
// Method 1 | |
$start = microtime( true ); | |
for($i = 0; $i <= $cnt; $i++) | |
{ | |
if($c[$i] === $rnd) | |
{ | |
echo 'Method #1'; | |
break; | |
} | |
} | |
_report($start); | |
// Method 2 | |
$start = microtime( true ); | |
if(in_array($rnd, $c)) { | |
echo 'Method #2'; | |
} | |
_report($start); | |
// Method 3 | |
$start = microtime( true ); | |
$flip = array_flip($c); | |
for($i = 0; $i <= $cnt; $i++) | |
{ | |
if(isset($flip[$rnd])) | |
{ | |
echo 'Method #3'; | |
break; | |
} | |
} | |
_report($start); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of output:
Results will vary every time, depends on the position of the value into the array. But method #2 (
in_array()
) seems the more reliable. While searching I have found some that suggest the usage ofarray_flip()
but then they do not include the function in the benchmark, which in a real-world example it is not correct. The above is just an attempt to emulate a more practical situation.