In this article, we are going to learn different techniques to find the maximum value of an array in C#. At the end of this article, we will do a performance benchmark to check which is the faster approach. 

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Preparing Our Source Code

Before we start looking for our maximum value, we should create our array of elements and fill it with some random values:

var sourceArray = new int[] { 3, 7, 23, 40, 37, 9, 19 };

Now that we have our environment ready, let’s see some approaches.

Using Enumerable.Max to Find the Maximum Value of an Array

Max is an extension method to the IEnumerable interface that requires no parameters and returns the largest value in the sequence of elements:

return sourceArray.Max(); //Output 40 

If we have an array of string, the output will be the first in alphabetical order. It means that this method doesn’t work only with arrays of int, but, with any kind of object that implements the System.IComperable interface.

Maximum Value of an Array Using OrderByDescending

The System.Linq allows us to get the maximum value from an array after ordering it in a descending form:

return sourceArray.OrderByDescending(x => x).First();

Different from the Enumerable.Max approach, this approach doesn’t require elements to be an implementation of IComperable interface. However, it requires a lambda expression as a parameter indicating which property we want to use to compare.

The OrderByDescending method returns an Enumerable in descending order. Based on this, we just need to call First() to get the largest element.

Enumerable.MaxBy

Since .NET 6, we can replace the above approach with Enumerable.MaxBy

return sourceArray.MaxBy(x => x);

With this method, we don’t need to order our array and then return the first element. All we have to do is to call the method passing our lambda expression as a parameter, indicating which property we want to compare.

Similar to the method we use to get the maximum element, .NET 6 also provides a method to return the minimum element:

return sourceArray.MinBy(x => x);

Using Iteration Statement

Let’s create a new GetLargerstElementUsingFor method to show how we can find the maximum element of an array with a simple iteration:

public int GetLargestElementUsingFor(int[] sourceArray)
{
    int maxElement = sourceArray[0];
    for (int index = 1; index < sourceArray.Length; index++)
    {
        if (sourceArray[index] > maxElement)
            maxElement = sourceArray[index];
    }

    return maxElement;
}

To find the maximum element manually, first, we need to initialize the maxElementvariable filling it with our array’s first element.

Then we loop through our array checking if each element is greater than our maxElement value. Once the element is greater, we should assign its value to maxElement.

When we finish the loop we just need to return the maxElement variable.

Benchmark

For this article, we are going to implement two benchmarks to show the difference of performance between all of the above approaches using arrays with 100 thousand different elements.

For the first benchmark, we are going to use an array of int.

That said, let’s create an array in the benchmarks class:

private static readonly int[] sourceArray = FillElements(1000 * 100);

And, let’s implement a method responsible to populate our array with random numbers:

private static int[] FillElements(int length)
{
    var sourceArray = new int[length];
    for (int index = 0; index < length; index++)
        sourceArray[index] = new Random().Next(0, 1000);

    return sourceArray;
}

After we run the first benchmark, we can inspect the result:

|                                  Method |        Mean |     Error |    StdDev |
|---------------------------------------- |------------:|----------:|----------:|
|               GetLargestElementUsingMax |   639.36 us | 11.943 us | 10.588 us |
| GetLargestElementUsingOrderByDescending | 1,391.94 us | 19.638 us | 18.370 us |
|             GetLargestElementUsingMaxBy |   818.87 us | 15.448 us | 20.623 us |
|               GetLargestElementUsingFor |    69.89 us |  1.035 us |  0.865 us |

Note that, using the for loop is much faster than any other approach. Being almost twelve times faster than the second-best approach and almost twenty times faster than the worst.

Anyway, these results are in microseconds. In other words, the worst scenario took us around 0.001391 seconds to find the maximum element in an array of 100 thousand integers.

Let’s compare this benchmark result with an array of 100 thousand objects instead of integers:

|                                  Method |     Mean |     Error |    StdDev |
|---------------------------------------- |---------:|----------:|----------:|
|               GetLargestElementUsingMax | 8.416 ms | 0.0997 ms | 0.0933 ms |
| GetLargestElementUsingOrderByDescending | 8.899 ms | 0.1099 ms | 0.0974 ms |
|             GetLargestElementUsingMaxBy | 8.613 ms | 0.1005 ms | 0.0940 ms |
|               GetLargestElementUsingFor | 7.608 ms | 0.0732 ms | 0.0572 ms |

Different from the integer array, this time, our results are in milliseconds (0.001 seconds) and our best approach keeps being the iteration statement, achieving 10% faster than using Enumerable.Max approach.

Conclusion

In this article, we’ve seen that we have many ways to find the maximum value from an array. 

We’ve seen two performance benchmarks that show us the fastest way to find this value, and, even if we choose the worst way, it wouldn’t be too prejudicial for our project, once the differences are in micro and milliseconds. However, it is up to us to decide if we should take this difference into account and choose which is the best approach when we are writing our code.