代码之家  ›  专栏  ›  技术社区  ›  Ans

Excel vba:为每个对象类设置一个长变量会显著增加执行时间

  •  2
  • Ans  · 技术社区  · 7 年前

    我有一个使用 Client 类:创建具有 100 000 Clients 并在阵列上循环 100 次,每次设置不同的随机数 客户 .

    Sub start()
        Application.ScreenUpdating = False
    
        Dim j As Long
    
        Dim clientsColl() As Client
        ReDim clientsColl(1 To 100000) As Client
    
        For j = 1 To 100000
            Set clientsColl(j) = New Client
    
            clientsColl(j).setClientName = "Client_" & j
        Next
    
        Dim clientCopy As Variant
    
        MsgBox ("simulations start")
        Dim i As Long
        For i = 1 To 100
            For Each clientCopy In clientsColl
                clientCopy.setSimulationCount = 100
                clientCopy.generateRandom
            Next
        Next
    
        Application.StatusBar = False
        Application.ScreenUpdating = True
    
        MsgBox ("done")
    End Sub
    

    但是,根据行是否 clientCopy.setSimulationCount = 100 是否被注释掉。如果这一行被注释掉,则在 simulations start MsgBox 16 seconds 运行。但是,如果该行没有注释掉,并且执行了第二个循环 2 minute 35 seconds 运行。

    这是 客户 类,使用的 Let 属性:

    Private simulationCount As Long
    
    Public Property Let setSimulationCount(value As Double)
        simulationCount = value
    End Property
    
    Private randomNumber As Double
    
    Public Sub generateRandom()
        randomNumber = Rnd()
    End Sub
    

    所以它只是把数字 100 每个客户端内部。为什么它会将执行时间增加九倍?

    1 回复  |  直到 7 年前
        1
  •  3
  •   S Meaden    7 年前

    您已定义 clientCopy 作为一个 Variant ,必须在运行时为每个方法调用解析。请更改为类型 Client 重新计时。

    好的,我已经重新阅读了问题和评论,为了加快循环,因此对其进行更改

    Option Explicit
    
    Sub start()
        Application.ScreenUpdating = False
    
        Dim j As Long
    
        Dim clientsColl() As Client
        ReDim clientsColl(1 To 100000) As Client
    
        For j = 1 To 100000
            Set clientsColl(j) = New Client
    
            clientsColl(j).setClientName = "Client_" & j
        Next
    
        'Dim clientCopy As Variant
        Dim clientCopy As Client
    
        MsgBox ("simulations start")
        Dim i As Long
        For i = 1 To 100
            Dim lClientLoop As Long
            For lClientLoop = LBound(clientsColl) To UBound(clientsColl)
            'For Each clientCopy In clientsColl
                Set clientCopy = clientsColl(lClientLoop)
                clientCopy.setSimulationCount = 100
                clientCopy.generateRandom
            Next
        Next
    
        Application.StatusBar = False
        Application.ScreenUpdating = True
    
        MsgBox ("done")
    End Sub