HotDog's Blog

Hotdog (Robert Verpalen) about C# and vb.net

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

OctNovember 2009Dec
SMTWTFS
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

Articles

Archives

Topics

CONTACT

Fun but useful linkies

General

VS 2005

Wolfenstein ET

When using structures keep in mind that when a struct. variable is given a value, the entire stack memory of that structure is copied. (For a class only a pointer is assigned)

In other words, unless using pointers, don't use struct reassingment inside loops. To test the difference, try the following code:

        Shared Sub TestStructSpeed()
            Dim T, i As Integer
            Dim dummy = New a, a As a
            Do
                T = Environment.TickCount
                For i = 0 To 10000000
                    a = dummy
                    dummy = a
                Next
                T = Environment.TickCount - T
                Console.WriteLine("Milliseconds taken: {0}", T)
                Console.Write("Run again? ")
                If Not Console.ReadLine().ToLower().StartsWith("y") Then Exit Do
            Loop
        End Sub

 

Run this code once with a class:

Class A

Public A, B, C As Integer

End Class

 

and once with a struct:

Structure A

Public A, B, C As Integer

End Structur

 

The biggest no go is using structures with managed types. Run the code again with:

Structure A

Public A, B, C As Object

End Structure

 

When a structure uses managed types (all object derrived types), it can no longer put on the stack in sequential order, causing additional overhead. Pointers in unsafe code can also only be used on structures with unmanaged types.

The advantage of structures is that they can be created a lot faster than classes. Change the loop in the testcode to:

For i = 0 To 10000000

a = New a

Next

And run the test once with structs and once with classes. This time those structs will be a lot faster.

 

Conclusion: Structures in .Net can best be used for quicly storing data without passing to and from other variables/methods to stay effective.

posted on Wednesday, August 11, 2004 8:06 AM