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 ("");}