This question derives from the reason I asked my last question on foreach loops. I have a large string array (say in the thousands), and I want to iterate through the array and also be able to break out based on a certain condition, and I need optimal performance.
Some example code:
for(int i = 0; i < array.length && flag == true; i++){
//Processing and set flag
}
//..or
foreach(string item in array){
//processing...set flag
if(!flag)
break;
}
Which way would be less expensive?
You can always benchmark them. Use a
Stopwatchand iterate over, say, ten million iterations to see which goes faster.What I think you’ll find, though, is that the two are nearly identical since the JIT compiler optimizes
foreachon an array to basically afor.flevine100 is actually right that in general a
foris slightly more efficient than aforeachfor types whoseGetEnumeratormethods create a new object implementingIEnumeratororIEnumerator<T>(due to the memory allocation and method call overhead); this is less the case for most of the collections inSystem.Collections.Generic, however, due to their explicitIEnumerableimplementation using value type enumerators (not to mention that theforeachconstruct does not actually require anIEnumerableimplementation in the first place).It’s even less the case for arrays specifically because they are fixed-size and therefore trivial to optimize by the JIT compiler.