为什么C#Array.BinarySearch如此之快?

Dan*_*iel 12 c# performance search icomparable

我在C#中实现了一个非常简单的 binarySearch实现,用于在整数数组中查找整数:

二进制搜索

static int binarySearch(int[] arr, int i)
{
    int low = 0, high = arr.Length - 1, mid;

    while (low <= high)
    {
        mid = (low + high) / 2;

        if (i < arr[mid])
            high = mid - 1;

        else if (i > arr[mid])
            low = mid + 1;

        else
            return mid;
    }
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

当比较它与C#的母语Array.BinarySearch(),我可以看到Array.BinarySearch()快两倍以上为我的功能,每一次.

Array.BinarySearch上的 MSDN :

使用由Array的每个元素和指定对象实现的IComparable通用接口,搜索特定元素的整个一维排序数组.

是什么让这种方法如此之快?

测试代码

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Random rnd = new Random();
        Stopwatch sw = new Stopwatch();

        const int ELEMENTS = 10000000;
        int temp;

        int[] arr = new int[ELEMENTS];

        for (int i = 0; i < ELEMENTS; i++)
            arr[i] = rnd.Next(int.MinValue,int.MaxValue);

        Array.Sort(arr);

        // Custom binarySearch

        sw.Restart();
        for (int i = 0; i < ELEMENTS; i++)
            temp = binarySearch(arr, i);
        sw.Stop();

        Console.WriteLine($"Elapsed time for custom binarySearch: {sw.ElapsedMilliseconds}ms");

        // C# Array.BinarySearch

        sw.Restart();
        for (int i = 0; i < ELEMENTS; i++)
            temp = Array.BinarySearch(arr,i);
        sw.Stop();

        Console.WriteLine($"Elapsed time for C# BinarySearch: {sw.ElapsedMilliseconds}ms");
    }

    static int binarySearch(int[] arr, int i)
    {
        int low = 0, high = arr.Length - 1, mid;

        while (low <= high)
        {
            mid = (low+high) / 2;

            if (i < arr[mid])
                high = mid - 1;

            else if (i > arr[mid])
                low = mid + 1;

            else
                return mid;
        }
        return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

检测结果

+------------+--------------+--------------------+
| Attempt No | binarySearch | Array.BinarySearch |
+------------+--------------+--------------------+
|          1 | 2700ms       | 1099ms             |
|          2 | 2696ms       | 1083ms             |
|          3 | 2675ms       | 1077ms             |
|          4 | 2690ms       | 1093ms             |
|          5 | 2700ms       | 1086ms             |
+------------+--------------+--------------------+
Run Code Online (Sandbox Code Playgroud)

And*_*rew 12

在Visual Studio外部运行时,您的代码更快:

你和阵列的:

From VS - Debug mode: 3248 vs 1113
From VS - Release mode: 2932 vs 1100
Running exe - Debug mode: 3152 vs 1104
Running exe - Release mode: 559 vs 1104
Run Code Online (Sandbox Code Playgroud)

数组的代码可能已经在框架中进行了优化,但也比你的版本做了更多的检查(例如,如果arr.Length大于你的版本可能会溢出int.MaxValue / 2),并且如前所述,它的设计适用于各种类型,而不仅仅是int[].

因此,基本上,只有在调试代码时它才会变慢,因为Array的代码总是在发布中运行,并且在后台控制较少.

  • @ M.Hassan二分搜索需要排序数组作为输入.排序不包括在时间中. (2认同)