Thursday, June 4, 2009

C#-For and VB.NET-For

Yesterday I wondered why on earth my simple VB.NET-For-loop produced an error:

Dim collection As New List(Of Integer)
collection.Add(1)
collection.Add(2)
collection.Add(3)
collection.Add(4)
collection.Add(5)

For i As Integer = 0 To collection.Count - 1
Console.WriteLine(collection(i))

If collection(i) = 2 Then
collection.RemoveAt(i)
End If
Next

I’m coming from a Java / C#-background, so I tried the same loop in C#:

var collection = new List<int>();
collection.Add(1);
collection.Add(2);
collection.Add(3);
collection.Add(4);
collection.Add(5);

for (int i = 0; i < collection.Count; i++) {
Console.WriteLine(collection[i]);

if (collection[i] == 2) {
collection.RemoveAt(i);
}
}

Et voilá, the result is what I wanted. So I made my discovery of the day: C#-For isn’t VB.NET-For.

In the cold light of day and using the debugger, it seems obvious that the VB.NET-For doesn’t check the condition on every iteration. It just duplicates the loop as often as it is stated in the For-statement.

The C#-construct is smarter as it checks in every iteration if the condition is true. But if it’s true that this is the difference between the two Fors, then the C#-loop must be slower. So, let’s check it out:

Dim start = DateTime.Now

For i As Integer = 0 To 1000000000
' nothing
Next

Console.WriteLine(Now.Subtract(start).ToString())

Vs.

var start = DateTime.Now;

for (int i = 0; i < 1000000000; i++) {
// nothing
}

Console.WriteLine(DateTime.Now.Subtract(start).ToString());

And indeed, the VB.NET-For-loop wins on my system with 3.734s to 4.687s!

No comments:

Post a Comment