I have this array : var arr = new int[] { 1, 1, 0, -1, -1 }; where I need to count the number of positives, negatives and zeros numbers.
I did it with foreach loop and with Linq and I tried to compare the performance between the two methods by using the Stopwatch here is my code:
int pos = 0, neg = 0, zeros = 0;
int p = 0, n = 0, z = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
pos = arr.Sum(e => e > 0 ? 1 : 0);
neg = arr.Sum(e => e < 0 ? 1 : 0);
zeros = arr.Sum(e => e == 0 ? 1 : 0);
sw.Stop();
Stopwatch sw2 = new Stopwatch();
sw2.Start();
foreach (var item in arr)
{
if (item > 0) p++;
else if (item < 0) n++;
else z++;
}
sw2.Stop();
Console.WriteLine("Elapsed={0}", sw.Elapsed); //Elapsed=00:00:00.0008311
Console.WriteLine("Elapsed2={0}", sw2.Elapsed); //Elapsed2=00:00:00.0000028
The results showed me that the foreach loop where a lot better (28ms) than the Linq method (8311ms), So my question is why there is all this difference in performance?
I even tried to make three foreach loop, one to count the negatives, one to count the positives and the third to count the zeros, but the performance was still good than the Linq method!
Thanks in advance for your help!