tags:

views:

39

answers:

2

About using structure constructors; are those two code blocks equal in performance?

With constructor:

Dim pt As Point
For i As Integer = 1 To 1000
    pt = New Point(i, i)
Next

No constructor:

Dim pt As Point
For i As Integer = 1 To 1000
    pt.X = i
    pt.Y = i
Next

First one is shorter, especially if constructor would have more arguments, but is it wise to use it in loops (let say game loop fired 60 times per second)? Or are those two compiled to the same machine code?

+1  A: 

I'd hope these give the same machine code, assuming Point is a .NET structure (a value type, as opposed to a reference type), and assuming the Point constructor does nothing but assign to the X and Y fields. I'd expect the JIT to inline the call Point constructor.

There is, however, a difference in the IL, because the compiler doesn't inline the constructor. As you'd expect, the first piece of code makes 1000 calls to the constructor, whereas the second makes 1000 pairs of field store operations.

As always with "which is faster?" questions, write them both and time them. Stopwatch is useful for this.

Tim Robinson
+4  A: 
Hans Passant
Thanks. I was hoping to get an answer like this. I love to code for clarity but the old "is this optimal" keeps popping in my head.
Hugo Riley