2017-12-27 628 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

相關問題