2017-12-27 614 views
2

我有一个主子,使得使用一个Client类:与100 000Clients创建一个数组并循环阵列之上100次,每次设置不同的随机数到每个ClientExcel VBA中:设置一个长变量为每个对象类显着地增加执行时间

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 startMsgBox需要16 seconds才能运行。但是,如果该行未被注释掉并且被执行,则第二个循环将运行2 minute 35 seconds

这里的Client类的内部,使用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每个客户端里面。为什么它会将执行时间增加九倍?

+0

如果你的代码作品应该被移动到另一个论坛得到改善。 – 2017-12-27 13:58:26

+0

任何代码都可以通过经常重复来降低速度。这不是快速的代码。考虑将参数类型从Double更改为Long,这样您就不需要支付两个昂贵的浮点转换。避免变种,使用客户端。 –

+0

Hmm,Dim obj由于客户端=客户端循环内循环应始终工作。使用For..To而不是For Each应始终有效。 –

回答

2

您已将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 
+0

我无法在数组中使用Client循环。我无法使用Collection,因为我尝试了它,运行速度更慢。 – Ans

+1

看到我的代码,是的,你可以。 –

+0

@S Meaden你使用'for'循环来代替每个''。我已经在这个论坛上被告知数千次了,对于每个循环来说,要快得多,并且必须使用它来代替'for',即使它需要使用'Variant'。 – Ans

相关问题