2010-01-06 52 views
5

在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 

除非我喜欢从其他模块调用子慢下来的静态变量的使用不会发生:

我这个代码在一个测试应用程序复制问题上面的例子。

+0

如果在SampleSub2中动态声明Counter1和Counter2,执行时间会受到怎样的影响? – xpda 2010-01-06 04:00:20

+0

还是比静态更快...我添加了一个例子。 – SteveGSD 2010-01-06 04:34:09

回答

5

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

但是,如果您正在初始化并同时声明一个静态局部变量,实际发生的情况是编译器围绕它附带一个Monitor类,以确保它不能被多个线程初始化时间。

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

+0

当我刚刚做“Static Counter1 as integer = 0”时,我得到相同的+500毫秒 – SteveGSD 2010-01-06 04:12:35

+0

看起来减速只在模块中使用时才会发生。我刚刚添加的示例在subs1包含在form1类中时工作速度相同,但是当我将subs放入公共模块时,仅在静态方法上出现减速。 – SteveGSD 2010-01-06 04:35:26

+0

Static counter3 As Integer = 0仍然将变量声明与初始化语句组合在一起。 – womp 2010-01-06 04:37:54

相关问题