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