成员级别的dim与程序级别的静态有什么区别?

时间:2010-01-06 03:25:18

标签: static vb.net

在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

我在大约7秒内运行了大约800万次循环(处理了更多数据),并且在计数器上使用静态方法实际上需要大约500ms。静态方法是否提供更好的内存管理?它为什么慢?

此外,我声明我的对象在成员级别上或者至少在外部用于循环时重复使用,例如:

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

除非我从另一个模块中调用sub,如上例所示,否则不会出现使用静态变量的速度变慢。

1 个答案:

答案 0 :(得分:5)

静态局部变量是VB.Net的一个奇怪特征。编译它们时,它们只是由幕后的类级静态变量表示。

但是,如果你同时初始化并声明一个静态局部变量,那么实际发生的是编译器在它周围粘贴一个Monitor类,以确保它不能同时由多个线程初始化

您可能会看到这台显示器的开销。尝试从声明性语句中删除初始化,看看是否注意到性能提升。