DEV Community

Cover image for .Net BinarySearch is fast, but can we make it faster?
Frederik Van Lierde
Frederik Van Lierde

Posted on

.Net BinarySearch is fast, but can we make it faster?

The short answer is yes, up to 25%

We all know that in the .Net Framework, the BinarySearch is fast to search in List<>, but can we make it even faster?

The Question

We have a List with 1.000.000 numbers.
We create a function to see if a number exists in the collection

public bool ExistBinarySearch()
{
    return _numbers.BinarySearch(numberToSearch) >= 0;
}
Enter fullscreen mode Exit fullscreen mode

The Faster Binary Search is

public bool ExistFasterBinarySearch()
{
    int low = 0;
    int high = _numbers.Count - 1;

    while (low <= high)
    {
        int mid = (low + high) / 2;
        if (_numbers[mid] == numberToSearch)
            return true;
        else if (_numbers[mid] < numberToSearch)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode

The Results

The FasterBinarySearch wins.

Image description

Top comments (0)