我有一个主子,使得使用一个Client
类:与100 000
Clients
创建一个数组并循环阵列之上100
次,每次设置不同的随机数到每个Client
。Excel 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 start
MsgBox
需要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
每个客户端里面。为什么它会将执行时间增加九倍?
如果你的代码作品应该被移动到另一个论坛得到改善。 – 2017-12-27 13:58:26
任何代码都可以通过经常重复来降低速度。这不是快速的代码。考虑将参数类型从Double更改为Long,这样您就不需要支付两个昂贵的浮点转换。避免变种,使用客户端。 –
Hmm,Dim obj由于客户端=客户端循环内循环应始终工作。使用For..To而不是For Each应始终有效。 –