在Visual Basic 2008中,有两种不同的方式,我知道要完成同样的事情:在成员级别会员级别的暗淡与程序级别的静态有什么区别?
的点心:
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
再有就是对程序级别的静态:
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
我运行一个循环约8万次通过这在约7秒(与所处理更多的数据),以及使用在柜台上的静态方法实际上需要约500ms的时间。静态方法是否提供更好的内存管理?为什么它更慢?
此外,我声明我的对象是与昏暗重新使用的部件的水平或至少外面的for循环,如:
Dim SampleObject as SampleClass
Public Sub SampleSub3()
SampleObject = TheQueue.Dequeue()
End Sub
我应该使用静态方法(这似乎是慢)在这样的情况下,还是我已经使用的成员级别方法暗淡?
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
除非我喜欢从其他模块调用子慢下来的静态变量的使用不会发生:
我这个代码在一个测试应用程序复制问题上面的例子。
如果在SampleSub2中动态声明Counter1和Counter2,执行时间会受到怎样的影响? – xpda 2010-01-06 04:00:20
还是比静态更快...我添加了一个例子。 – SteveGSD 2010-01-06 04:34:09