We aren't entirely off topic... too far... I hope.
First of all, the foreach example was just an example. There are plenty of others.
Depending on what you are doing the difference between a foreach and a for loop can be enough to make a difference. A foreach loop requires the instantiation of an IEnumerator (one hit per foreach loop). Then, in order to iterate a call is made to MoveNext, and if that returns true, a call is made Current to obtain the object, which must be stored in a variable. A foreach is also automatically wrapped in a structured exception handling block. The foreach loop (at least in C#... I'm not positive about VB) is optimized for arrays, but for all other IEnumerable types you will see a performance hit.
A foreach on an arraylist would compile from this:
Visual Basic:
For Each o As Object In myArrayList
If o Is SomeOtherObject Then
Return o
End If
Next
to
Visual Basic:
' IEnumerator instantiation
Dim i As IEnumerator = DirectCast(myArrayList, IEnumerator).GetEnumerator();
While i.MoveNext() 'Extra function call
Dim o As Object = i.Current
If o Is SomeOtherObject Then
Return o
End If
End While
There are a little more than half as many IL instructions in the equivalent for loop, and that isn't counting the function calls to GetEnumerator and MoveNext.
Using VB8 Express console application, I did a quick benchmark with an unsorted ArrayList of 100,000,000 objects where the ArrayList was searched linearly for a specific object inserted at a random position using a For and For Each loop with a release build, and then repeated the test with For Each first and then For after. The results are as follow:
Code:
For ForEach Ratio
78 547 7.012820513
94 656 6.978723404
78 547 7.012820513
47 313 6.659574468
31 219 7.064516129
16 46 2.875
63 437 6.936507937
15 157 10.46666667
31 172 5.548387097
47 312 6.638297872
47 281 5.978723404
As you can see, a ForEach loop over an ArrayList takes approximately six to seven times as long as a For loop. I would call that a signifigant difference in performance. The IL for C# and VB ForEach loops would be very similar, so you would see this difference in C# also.
Is this essential knowlege? No, but it sure helps. Is this something we should expect a new programmer to know. If you ask me, the answer is
eventually.