In this thread we discussed about performance analysis of the for loop
and foreach
.
Which one gives better performance - the for
or foreach
?
Here are two simple methods:
public static void TestFor()
{
Stopwatch stopwatch = Stopwatch.StartNew();
int[] myInterger = new int[1];
int total = 0;
for (int i = 0; i < myInterger.Length; i++)
{
total += myInterger[i];
}
stopwatch.Stop();
Console.WriteLine("for loop Time Elapsed={0}", stopwatch.Elapsed);
}
public static void TestForeach()
{
Stopwatch stopwatchForeach = Stopwatch.StartNew();
int[] myInterger1 = new int[1];
int totall = 0;
foreach (int i in myInterger1)
{
totall += i;
}
stopwatchForeach.Stop();
Console.WriteLine("foreach loop Time Elapsed={0}", stopwatchForeach.Elapsed);
}
Then I ran the above code the result was foreach loop Time Elapsed=00:00:00.0000003, for loop Time Elapsed= 00:00:00.0001462. I think we want high performance code. We would use foreach