Problem
Recently when implementing a project interface, I found that when the array is too large, the data return speed is a bit slow. The maximum response time for interface data return is 2 seconds. After repeated debugging, it was found that the longest part of the code segment is in the in_array()
function.
Solution process
I found an article on stackoverflow that provided me with solution ideas
- which is faster, array_key_exists or array_search?
The article says:
array_key_exists
is much faster.array_search
must traverse the whole array, so it is O(n).array_key_exists
is a hash table lookup , so it is O(1).
----Separating line----
I think it's faster for PHP to check for keys (
array_key_exists()
or simplyisset($array[$ key]))
. To search for a value, PHP must cycle through the array; to search for a key PHP will use a hash function.
The array is used to save the user account and is never destroyed and stored in memory.
Original array$array=array('account1','account2','$account3');
Modified array$array=array('account1'=>0,'account2' =>0,'$account3'=>0)
Use isset($array[$account]))
to detect whether the account exists in the array
Summary
Due to the in_array()
function Traversing the array is O(n), and the time consumption will increase as n (array length) increases. Therefore, efficiency issues should be considered when using the in_array()
function for large arrays.
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });When faced with large array queries, you should try to use key queries instead of value queries in PHP.
The above introduces the performance issues of in_array large array query, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.