Search code examples
c#arraysperformanceprocessing-efficiency

What is the efficient way to check if an item is present in an array with up to 1000000 items ore more


If you want to check if an int value is present in an int[] array with up to 1000000 items what is the most efficient way to do this and minimize CPU cycles?

int[] values = {1, 2, 3, 4};
value = 4

I know of using a for loop or something like this:

values.Contains(value);
Array.Exists(values , i => i==value );
Array.IndexOf(values, value) != -1;

Solution

  • Because your array is sorted the best way is to use the BinarySearch method.

    bool IsInArray(int[] values, int value)
    {
        var index = Array.BinarySearch(values, value);
        return (index >= 0);
    }
    

    If the array is not sorted then the other 3 options you listed are all likely going to perform about exactly the same, I would just use values.Contains(value); as that is the simplest choice.