In Visual Basic 2008, there are two different ways that I know to accomplish the same thing:
Member Level Size:
Dim counter1 as integer = 0
Dim counter2 as integer = 180
Public Sub SampleSub1()
Counter1 += 1 : If (Counter1 > 14) Then Counter1 = 0
Counter2 += 1 : If (Counter2 > 240) Then Counter2 = 0
End Sub
Then at the procedure level there is static:
Public Sub SampleSub2()
Static Dim counter1 as integer = 0
Static Dim counter2 as integer = 180
Counter1 += 1 : If (Counter1 > 14) Then Counter1 = 0
Counter2 += 1 : If (Counter2 > 240) Then Counter2 = 0
End Sub
I start a loop about 8 million times through this after about 7 seconds (with a lot of data being processed), and using the static method on the counters actually takes about 500 ms longer. Does the static method provide better memory management? Why is it slower?
In addition, I declare my objects that are reused with dim at member level or at least outside for loops, for example:
Dim SampleObject as SampleClass
Public Sub SampleSub3()
SampleObject = TheQueue.Dequeue()
End Sub
Should I use the Static method (which seems to be slower) in such situations, or the dim on member level method that I already use?
:
Public Class Form1
Dim EndLoop As Integer = 50000000
Dim stopwatch1 As New Stopwatch
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
stopwatch1.Reset()
stopwatch1.Start()
For cnt As Integer = 1 To EndLoop
test1()
Next
stopwatch1.Stop()
Label1.Text = "Loop1: " & stopwatch1.ElapsedMilliseconds
stopwatch1.Reset()
stopwatch1.Start()
For cnt As Integer = 1 To EndLoop
test2()
Next
stopwatch1.Stop()
Label2.Text = "Loop2: " & stopwatch1.ElapsedMilliseconds
End Sub
End Class
Public Module TestModule
Dim counter1 As Integer = 0
Dim counter2 As Integer = 180
Public Sub test1()
counter1 += 1 : If (counter1 > 14) Then counter1 = 0
counter2 += 1 : If (counter2 > 240) Then counter2 = 0
COW1(counter1, counter2)
End Sub
Public Sub test2()
Static counter3 As Integer = 0
Static counter4 As Integer = 180
counter3 += 1 : If (counter3 > 14) Then counter3 = 0
counter4 += 1 : If (counter4 > 240) Then counter4 = 0
COW1(counter3, counter4)
End Sub
Public Sub COW1(ByVal counter1 As Integer, ByVal counter2 As Integer)
End Sub
End Module
, sub , .