Last active
September 9, 2022 01:12
-
-
Save rotexdegba/9751711 to your computer and use it in GitHub Desktop.
Alternative implementation of in_array using either isset or array_key_exists. This approach requires restructuring the original array.
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 | |
//This isset optimization is not suitable for arrays that contains null values. | |
/* | |
$a = array('a' => null); | |
isset($a['a']); // Will be FALSE | |
array_key_exists('a', $a); // Will be TRUE | |
*/ | |
$total = 10000; | |
$paragraph = 'this is a sentence. Crud! $$$$!'; | |
$words = explode(' ', $paragraph); | |
// Create a bunch of letter entries | |
$sequence = []; | |
for ($j = 0; $j < 10000; $j++) { | |
$sequence[] = 'a' . $j; | |
} | |
$s = microtime(true); | |
for ($j = 0; $j < $total; $j++) { | |
foreach ($words as $word) { | |
in_array(strtolower($word), $sequence); | |
} | |
} | |
echo "in_array: " . (microtime(true) - $s) . "\n"; | |
// Convert the array to a hash | |
$hash = array_fill_keys($sequence, true); | |
$s = microtime(true); | |
for ($j = 0; $j < $total; $j++) { | |
foreach ($words as $word) { | |
isset($hash[strtolower($word)]); | |
} | |
} | |
echo "isset: " . (microtime(true) - $s) . "\n"; | |
$s = microtime(true); | |
for ($j = 0; $j < $total; $j++) { | |
foreach ($words as $word) { | |
array_key_exists(strtolower($word), $hash); | |
} | |
} | |
echo "array_key_exists: " . (microtime(true) - $s) . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks