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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay