Home > Backend Development > PHP Tutorial > in_array large array query performance issues

in_array large array query performance issues

WBOY
Release: 2016-07-29 08:59:10
Original
1759 people have browsed it

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 simply isset($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.

When faced with large array queries, you should try to use key queries instead of value queries in PHP.

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template