For vs For Each loops – Performance Issues.

26 Jan

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.

The speed of a For or For Each loop usually depends on the number of items in the list, the type of list ( array, arraylist, generic list, dictionary) etc.

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.

loops

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.

Yours truly.

About these ads

One Response to “For vs For Each loops – Performance Issues.”

  1. Amit March 10, 2010 at 5:33 am #

    its realy good one.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: