What is the best way to iterate through a strongly-typed generic List?


Question

What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET?

1
15
8/19/2008 12:27:28 AM

Accepted Answer

For C#:

foreach(ObjectType objectItem in objectTypeList)
{
    // ...do some stuff
}

Answer for VB.NET from Purple Ant:

For Each objectItem as ObjectType in objectTypeList
    'Do some stuff '
Next
30
4/21/2010 6:07:30 PM

With any generic implementation of IEnumerable the best way is:

//C#
foreach( var item in listVariable) {
    //do stuff
}

There is an important exception however. IEnumerable involves an overhead of Current() and MoveNext() that is what the foreach loop is actually compiled into.

When you have a simple array of structs:

//C#
int[] valueTypeArray;
for(int i=0; i < valueTypeArray.Length; ++i) {
     int item = valueTypeArray[i];
     //do stuff
}

Is quicker.


Update

Following a discussion with @Steven Sudit (see comments) I think my original advice may be out of date or mistaken, so I ran some tests:

// create a list to test with
var theList = Enumerable.Range(0, 100000000).ToList();

// time foreach
var sw = Stopwatch.StartNew();
foreach (var item in theList)
{
    int inLoop = item;
}
Console.WriteLine("list  foreach: " + sw.Elapsed.ToString());

sw.Reset();
sw.Start();

// time for
int cnt = theList.Count;
for (int i = 0; i < cnt; i++)
{
    int inLoop = theList[i];
}
Console.WriteLine("list  for    : " + sw.Elapsed.ToString());

// now run the same tests, but with an array
var theArray = theList.ToArray();

sw.Reset();
sw.Start();

foreach (var item in theArray)
{
    int inLoop = item;
}
Console.WriteLine("array foreach: " + sw.Elapsed.ToString());

sw.Reset();
sw.Start();

// time for
cnt = theArray.Length;
for (int i = 0; i < cnt; i++)
{
    int inLoop = theArray[i];
}
Console.WriteLine("array for    : " + sw.Elapsed.ToString());

Console.ReadKey();

So, I ran this in release with all optimisations:

list  foreach: 00:00:00.5137506
list  for    : 00:00:00.2417709
array foreach: 00:00:00.1085653
array for    : 00:00:00.0954890

And then debug without optimisations:

list  foreach: 00:00:01.1289015
list  for    : 00:00:00.9945345
array foreach: 00:00:00.6405422
array for    : 00:00:00.4913245

So it appears fairly consistent, for is quicker than foreach and arrays are quicker than generic lists.

However, this is across 100,000,000 iterations and the difference is about .4 of a second between the fastest and slowest methods. Unless you're doing massive performance critical loops it just isn't worth worrying about.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon