Let's see just how inefficient for loops are compared to foreach. I'm going to create a list of integers and then execute two loops that reference the list elements three times. The stopwatch class will tell me how much time we can save by utilizing foreach.
Create a new console application.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ForEach
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
List<int> l = Enumerable.Range(1, 10000000).ToList<int>();
int x;
sw.Start();
for (int i = 0; i
< l.Count; i++)
{
x = l[i];
x = l[i] + 1;
x = l[i] * 2;
}
sw.Stop();
Console.WriteLine("for i took " + sw.ElapsedMilliseconds.ToString() + "ms");
sw.Restart();
foreach (int i in l)
{
x = i;
x = i + 1;
x = i * 2;
}
sw.Stop();
Console.WriteLine("for each took " + sw.ElapsedMilliseconds.ToString() + "ms");
Console.ReadKey();
}
}
}
No comments:
Post a Comment