Tip:
Structures are stored on the evaluation stack (not the managed heap)
when used in a method body.
Tip 2:
This gives Structures performance advantages—and sometimes hurts performance.
Example
Integer
Note:
The Simple Structure is created and used without calling its constructor (Sub New).
It is used in the same way as an Integer.
Program that uses Structure: VB.NET
Structure Simple
Public _position As Integer
Public _exists As Boolean
Public _lastValue As Double
End Structure
Module Module1
Sub Main()
Dim s As Simple
s._position = 1
s._exists = False
s._lastValue = 5.5
Console.WriteLine(s._position)
End Sub
End Module
Output
1
Performance
Here, a Structure called Box is allocated many times in a loop. The managed heap is not accessed. All the Box instances are stored in local variable memory. Next a Class called Ball is allocated in a similar loop.
For Loops
But:
On each iteration the managed heap is accessed.
This triggers garbage collection at intervals.
This reduces performance.
Program that times Structure: VB.NET
Structure Box
Public _a As Integer
Public _b As Boolean
Public _c As DateTime
End Structure
Class Ball
Public _a As Integer
Public _b As Boolean
Public _c As DateTime
End Class
Module Module1
Sub Main()
Dim m As Integer = 100000000
Dim s1 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
Dim b As Box
b._a = 1
b._b = False
b._c = DateTime.MaxValue
Next
s1.Stop()
Dim s2 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
Dim b As Ball = New Ball
b._a = 1
b._b = False
b._c = DateTime.MaxValue
Next
s2.Stop()
Dim u As Integer = 1000000
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
End Sub
End Module
Output
2.26 ns
8.20 ns
However, the Structure, when passed as an argument to a Function, will be slower. It is larger. The Class is only four bytes—or eight bytes, depending on the system. When more bytes are copied, Function calls are slower.
No comments:
Post a Comment