I’m sure one of you has come to a point where they thought, should I use a For loop or a For Each loop? And issues like which one is faster or which one is more effective usually arise. Well, a real developer should be thinking like “I can measure this.”, which is what I’m going to do here today.
I wrote this peace of code here (VB.Net) and used an arraylist and a generic list, both filled with integers from 0 to 1000 and measured the speed of writting all the numbers to the console window using For and For Each loops.
Imports System.Diagnostics Module Sample Sub Main() 'Dim list As New ArrayList Dim list As New List(Of Integer) For i As Integer = 0 To 1000 list.Add(i) Next 'Timer starts here Dim t As New Stopwatch t.Start() For Each i As Integer In list Console.WriteLine(i.ToString) Next ' For i As Integer = 0 To list.Count - 1 'Console.WriteLine(list(i).ToString) 'Next t.Stop() Console.WriteLine("LOOP time: " & t.ElapsedMilliseconds) Console.Read() End Sub End Module
Remove the comments appropriately if you are going to test it.
On my machine I got these statistics in milliseconds.
Now, these results does not necesarly mean that generic lists are slower than arraylists or For Each loops are slower than For loops. That is not the point of this post at all.
The point is just simple. You should learn to put your concerns to the test. So I welcome you to test your loops and see for yourself which one is better than the other, though personally I never even think about it. I just use the one I think is more appropriate depending on the situation.
Till next time.