List & lt; T & gt; linear search and binary search BinarySearch efficiency analysis, listbinarysearch

Source: Internet
Author: User

List <T> linear search and binary search BinarySearch efficiency analysis, listbinarysearch

Today, the List search function is used, so I wrote a test code to test the performance gap between linear search and binary search to determine which search method to choose.

Linear search: Contains, Find, and IndexOf are all linear searches.

Binary Search: BinarySearch. Because binary search must be effective for ordered arrays, you must call the Sort method of List before searching.

Conclusion: if the number of List items is small, linear search is faster than binary search. The more the number of items, the more obvious the advantage of the binary algorithm. You can select an appropriate search method based on the actual situation.

Test results:

Test code:

Private void button#click (object sender, EventArgs e) {TestFind (10); TestFind (30); TestFind (70); TestFind (100); TestFind (300 ); testFind (1000);} private void TestFind (int aItemCount) {listBox1.Items. add ("test: number of items in the list:" + aItemCount + ", 1 million queries"); int nTimes = 1000000; int nMaxRange = 10000; // Random number generation range: Random ran = new Random (); List <int> test = new List <int> (); for (int I = 0; I <aItemCount; I ++) {test. add (ran. next (nMaxRange);} int nHit = 0; DateTime start = DateTime. now; for (int I = 0; I <nTimes; I ++) {if (test. indexOf (ran. next (nMaxRange)> = 0) {nHit ++;} DateTime end = DateTime. now; TimeSpan span = end-start; listBox1.Items. add ("common search time:" + span. milliseconds + "ms, hits:" + nHit); nHit = 0; start = DateTime. now; test. sort (); for (int I = 0; I <nTimes; I ++) {if (test. binarySearch (ran. next (nMaxRange)> = 0) {nHit ++ ;}} end = DateTime. now; span = end-start; listBox1.Items. add ("binary search:" + span. milliseconds + "ms, hits:" + nHit); listBox1.Items. add ("");}

 

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.