In_array Large Array Query performance issues

Source: Internet
Author: User
Problem

Recently, when implementing a project interface, it was found that when the array was too large, the data returned at a slower pace. The interface data returns the longest reaction time of 2s, which is repeatedly debugged to find the portion of the code snippet that takes the longest time in the in_array() function.

Resolution process

In StackOverflow found an article to provide me with a solution to the idea
-which is faster, array_key_exists or Array_search?

The text says:

array_key_existsis much faster. array_searchmust traverse the whole array, so it's O (n). array_key_exists is a hash table lookup, so it is O (1).

----Split 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 would use a hash function.

The array is used to save the user account and has not been destroyed in memory.

Original array
$array=array('account1','account2','$account3');

The modified array
$array=array('account1'=>0,'account2'=>0,'$account3'=>0)

Use isset($array[$account])) to detect if an account exists in the array

Summarize

Because the in_array() function iterates through the array of queries, O (n) increases time-consuming with n (the length of the arrays). Therefore, the use of functions on large arrays in_array() should consider efficiency issues.

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 <= lines; i++) {$numbering. Append ($ ('
  • '). Text (i)); }; $numbering. FadeIn (1700); }); });

    The above describes the In_array large Array query performance issues, including the aspects of the content, I hope the PHP tutorial interested in a friend helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.