A frequent question in .NET interviews is about operations using arrays. In this article, we are going to learn how to sum up elements of an array in C#. After studying the different techniques, we are going to build a performance benchmark and check which one is the best approach to use in each scenario.

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

Let’s dive in

Preparing the Environment

First, let’s instantiate a new int array and fill it with some random elements:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

private static readonly int[] sourceArray = new int[] { 3, 9, 4, 23, 7, 15, 14, 2, 59, 4 };

If we are creating a .NET 6 (C# 10) Console Application, we don’t need to add the System.Linq namespace, however, if we are using an earlier version, we should add it:

using System.Linq;

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

Using Iteration to Sum Up Elements of an Array in C#

We are going to learn two techniques using the iteration statement. Let’s check it.

Using For Loop

Let’s create a ForLoop method to sum all the values in the array:

public int ForLoop(int[] sourceArray)
{
    var result = 0;
    for (int i = 0; i < sourceArray.Length; i++)
        result += sourceArray[i];

    return result;
}

This method receives an array as an input parameter and returns an integer representing the sum of all elements in the array. Inside it, we create a new result variable and assign zero to it. Then we iterate through the entire array and increment this variable with the sum of each element of the array. 

Using Foreach Loop

To use the foreach loop, we are going to create a new ForeachLoop method:

public int ForeachLoop(int[] sourceArray)
{
    var result = 0;
    foreach (var item in sourceArray)
        result += item;

    return result;
}

Similar to the previous technique, we define a result variable and, for each element in the array, sum the value and store it to this variable.

There’s no big difference between using for and foreach loop to achieve this result. Anyway, it is good to mention and study both methods.

Using Array Class to Sum the Array Elements

Another way to achieve this result is using the Array class:

public int ArrayForEach(int[] sourceArray)
{
    var result = 0;
    Array.ForEach(sourceArray, value => result += value);

    return result;
}

In this approach, we define a result variable assigning zero as its value. Then we use the ForEach method under the Array class, to sum all the elements.

The ForEach method receives the array we want to iterate as the first parameter, and as a second parameter, it receives an  Action delegate, which we can execute on each element.

Once the action passes through the entire array, we return the result variable.

Sum the Array Elements With System.Linq

The System.Linq namespace provides us with some classes and methods that allow us to sum every element in the array. Let’s check some of them. 

Enumerable.Sum

The easiest way to use Linq to sum the array elements is using the Sum method from the Enumerable static class:

return Enumerable.Sum(sourceArray);

Another way to use this same method is:

return sourceArray.Sum();

Note that this is an extension method. That said, both ways will execute the same method. We can check that if we right-click at the Sum method in both cases and go to the method definition.

If it is necessary, this method has some overloads that allow us to pass a Func to transform each element into a decimal, long, int or float. 

Enumerable.Aggregate

Let’s check how to sum the elements using Aggregate method:

return sourceArray.Aggregate((total, value) => total + value);

This method has a Func delegate as a parameter that applies an accumulator over the array.

This Func returns an integer representing the sum of those elements. It receives, as input, two variables – total and current. Respectively, the total means the accumulator and the current represents each value of the array.

Benchmark Comparison

For this article, we are going to implement a benchmark comparison with 1 million elements to see the performance difference between all these 6 approaches:

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

To make it easier to read, instead of writing 1000000, we can use 1000 * 1000.

Now, let’s define the FillElements method that is going to create these random elements:

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

    return randomArray;
}

After running the benchmark, we can inspect the result:

|             Method |       Mean |     Error |    StdDev |     Median |
|------------------- |-----------:|----------:|----------:|-----------:|
|       UsingForLoop |   618.1 us |  12.79 us |  29.38 us |   599.9 us |
|   UsingForeachLoop |   598.7 us |   5.11 us |   4.53 us |   597.5 us |
|  UsingArrayForEach | 2,328.0 us |  42.55 us |  52.26 us | 2,304.8 us |
| UsingEnumerableSum | 5,461.9 us |  77.17 us |  64.44 us | 5,444.3 us |
|      UsingArraySum | 5,428.7 us |  25.61 us |  22.70 us | 5,423.3 us |
|     UsingAggregate | 7,990.9 us | 157.04 us | 244.50 us | 7,864.8 us |

The fastest method is UsingForeachLoop followed by UsingForLoop with the difference of 20 us. In both cases, we are not using .NET built-in functions.

When we start using the built-in functions, we make it, at least, 1710 us slower. 

The slowest method (UsingAggregate) is 13 times slower than the fastest method, however, it is good to mention that we are talking about us (microseconds), which is equivalent to 0.000001 seconds in an array of 1 million elements. So, even though there are differences between these techniques, we can conclude that all execute pretty fast.

Conclusion

In this article, we’ve learned about many methods, to sum up, elements of an array. After a benchmark result, we’ve seen that using your implementation may be faster than using .NET built-in functions, however, it is up to us to decide which is the technique to use in our code. 

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!