Which code snippet will give better performance? The below code segments were written in C#.
1.
for(int tempCount=0;tempCount<list.count;tempcount++)
{
if(list[tempCount].value==value)
{
// Some code.
}
}
foreach(object row in list)
{
if(row.value==value)
{
//Some coding
}
}
Best Solution
Well, it partly depends on the exact type of
list
. It will also depend on the exact CLR you're using.Whether it's in any way significant or not will depend on whether you're doing any real work in the loop. In almost all cases, the difference to performance won't be significant, but the difference to readability favours the
foreach
loop.I'd personally use LINQ to avoid the "if" too:
EDIT: For those of you who are claiming that iterating over a
List<T>
withforeach
produces the same code as thefor
loop, here's evidence that it doesn't:Produces IL of:
The compiler treats arrays differently, converting a
foreach
loop basically to afor
loop, but notList<T>
. Here's the equivalent code for an array:Interestingly, I can't find this documented in the C# 3 spec anywhere...