LMSouq
php-dev Open

List of Big-O for PHP functions

KE
Kendall Hopkins
1 month ago
3 views
Problem Description
After using PHP for a while now, I've noticed that not all built-in PHP functions are as fast as expected. Consider these two possible implementations of a function that finds if a number is prime using a cached array of primes. //very slow for large $prime_array $prime_array = array( 2, 3, 5, 7, 11, 13, .... 104729, ... ); $result_array = array(); foreach( $prime_array => $number ) { $result_array[$number] = in_array( $number, $large_prime_array ); } //speed is much less dependent on size of $prime_array, and runs much faster. $prime_array => array( 2 => NULL, 3 => NULL, 5 => NULL, 7 => NULL, 11 => NULL, 13 => NULL, .... 104729 => NULL, ... ); foreach( $prime_array => $number ) { $result_array[$number] = array_key_exists( $number, $large_prime_array ); } This is because `in_array` is implemented with a linear search O(n) which will linearly slow down as `$prime_array` grows. Where the `array_key_exists` function is implemented with a hash lookup O(1) which will not slow down unless the hash table gets extremely populated (in which case it's only O(n)). So far I've had to discover the big-O's via trial and error, and occasionally [looking at the source code][1]. Now for the question... **Is there a list of the theoretical (or practical) big O times for all* the built-in PHP functions?** *or at least the interesting ones For example, I find it very hard to predict the big O of functions listed because the possible implementation depends on unknown core data structures of PHP: `array_merge`, `array_merge_recursive`, `array_reverse`, `array_intersect`, `array_combine`, `str_replace` (with array inputs), etc. [1]: https://stackoverflow.com/questions/2350361/how-is-the-php-array-implemented-on-the-c-level

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base