2
int[] testArray = new int[200000000];

Stopwatch st2 = new Stopwatch();
st2.Start();

for (var j = 0; j < testArray.Length; j++)
{

}

st2.Stop();

Console.WriteLine("Total milliseconds - FOR LOOP: {0}", st2.Elapsed.TotalSeconds);



Stopwatch st = new Stopwatch();
st.Start();

foreach (var arr in testArray)
{

}

st.Stop();

Console.WriteLine("Total milliseconds - FOREACH LOOP: {0}", st.Elapsed.TotalSeconds);

Results:

for: 0,7046522 seconds
foreach: 0,05508682 seconds

Why is my foreach faster? I thought that my for loop would be faster than the foreach

Kartik Chugh
  • 1,104
  • 14
  • 28
MrProgram
  • 5,044
  • 13
  • 58
  • 98

1 Answers1

3

The reason is explained in detailed in this article. it says that

In micro-benchmarking, introducing extra local variables with foreach-loops can impact performance. However, if those local variables are reused several times in the loop body, they can lead to a performance improvement.

Thus: The for-loop is faster than the foreach-loop if the array must only be accessed once per iteration.

You can realize this by including some operations in the loop and runs it again.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88