gpt4 book ai didi

static - 成员级别的 dim 和过程级别的 static 有什么区别?

转载 作者:行者123 更新时间:2023-12-01 00:04:40 28 4
gpt4 key购买 nike

在 Visual Basic 2008 中,我知道有两种不同的方法可以完成同一件事:

成员(member)级别的 Dim:

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 万次循环(处理更多数据),并且在计数器上使用静态方法实际上需要大约 500 毫秒的时间。静态方法是否提供更好的内存管理?为什么它更慢?

此外,我声明了我的对象,这些对象在成员级别或至少在 for 循环之外与 dim 一起重新使用,例如:
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

除非我像上面的示例那样从另一个模块调用子程序,否则不会出现使用静态变量的减速。

最佳答案

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

但是,如果您同时初始化和声明一个静态局部变量,实际发生的情况是编译器在其周围粘贴了一个 Monitor 类,以确保它不能同时被多个线程初始化。

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

关于static - 成员级别的 dim 和过程级别的 static 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2010760/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com