C# Sum an Array – Performance Analysis

Posted on Posted in C#, Programming

The problem on which mechanism to use in your programming has between some trouble for some areas, here I did an analysis on summing up an array of double. The goal is to choose the tradeoff between easiest of LINQ and performance of FOREACH, as we all know that LINQ implement the IEnumerable class. Here I create a test project to measure the time span on summing up the array base on difference array dimension, than write the results to a CSV file, where I pot a LINQ vs. FOREACH graph to see the tradeoff.



As you can see the LINQ can do the job in just one short line of code, whereas FOREACH need three line of code, but when to use which one, in what event? Therefore I create the following test program.

The test project record ticks or millisecond need to each sum up, first I think the result couldn’t be that much difference. But as the result come out, I was amazed to see that below 100,000 record the result are about the some, but when start to go beyond 100,000 time to sum up by LINQ double the time used by FOREACH.

Therefore giving the result, we can conclude that if summing up below 100,000 records, you can use LINQ for simplify and for 100,000 records above you should use FOREACH for performance.