非常interesing問題。
我嘗試檢查性能,但我沒有發現什麼快得多。梅比,這對你有用。
Sub TestArrMaxMin()
NrOfLoops = 100
'1 test
Start = Timer
For i = 1 To NrOfLoops
max_in_array
Next i
Debug.Print Timer - Start & " max_in_array Loops=" & NrOfLoops
'2 test
Start = Timer
For i = 1 To NrOfLoops
max_in_array_of_array
Next i
Debug.Print Timer - Start & " max_in_array_of_array Loops=" & NrOfLoops
'3 test
Start = Timer
For i = 1 To NrOfLoops
max_in_array_each_in
Next i
Debug.Print Timer - Start & " max_in_array_each_in Loops=" & NrOfLoops
End Sub
你幾乎不做修改子:
Public Sub max_in_array()
Dim VarArray(100, 100, 100) As Double
'Assign values to array
For i = 0 To 100
For j = 0 To 100
For k = 0 To 100
VarArray(i, j, k) = Rnd() 'This will be more complicated in the actual code
Next k
Next j
Next i
'Find the maximum
Dim IntMax As Double
IntMax = 0
For i = 0 To 100
For j = 0 To 100
For k = 0 To 100
If VarArray(i, j, k) > IntMax Then
IntMax = VarArray(i, j, k)
IntMaxAdr = i & "," & j & "," & k
End If
Next k
Next j
Next i
'Debug.Print "max = " & CStr(IntMax)
'Debug.Print "Maximum indices are " & IntMaxAdr
End Sub
Sub使用數組的數組(我有希望,這將是最快的,但不是:():
Public Sub max_in_array_of_array()
Dim VarArray(100, 100) As Double
Dim ArrayOfArrays(100) As Variant
'Assign values to array
For i = 0 To 100
For j = 0 To 100
For k = 0 To 100
VarArray(j, k) = Rnd() 'This will be more complicated in the actual code
Next k
Next j
ArrayOfArrays(i) = VarArray
Next i
'Find the maximum
Dim IntMax As Double
IntMax = 0
Dim IntMaxAdr As Integer
IntMaxAdr = 0
For i = 0 To 100
Max = Application.WorksheetFunction.Max(ArrayOfArrays(i))
If Max > IntMax Then
IntMax = ArrMember
IntMaxAdr = i
End If
Next i
'find addres
adr_i = IntMaxAdr
For j = 0 To 100
For k = 0 To 100
If IntMax = ArrayOfArrays(adr_i)(j, k) Then
adr_j = j
adr_k = k
Exit For
End If
Next k
Next j
'Debug.Print "max = " & CStr(IntMax)
'Debug.Print "Maximum indices are " & adr_i & "," & adr_j & "," & adr_k
End Sub
而去年使用每個,快一點:
Public Sub max_in_array_each_in()
Dim VarArray(100, 100, 100) As Double
'Assign values to array
For i = 0 To 100
For j = 0 To 100
For k = 0 To 100
VarArray(i, j, k) = Rnd() 'This will be more complicated in the actual code
Next k
Next j
Next i
'Find the maximum
Dim IntMax As Double
IntMax = 0
Dim ArrMemberIndex As Long
ArrMemberIndex = -1
For Each ArrMember In VarArray
ArrMemberIndex = ArrMemberIndex + 1
If ArrMember > IntMax Then
IntMax = ArrMember
IntMaxAdr = ArrMemberIndex
End If
Next
'calculate i,j,k
adr_i = IntMaxAdr Mod 101
adr_j = Int(IntMaxAdr/101) Mod 101
adr_k = Int(IntMaxAdr/(101^2))
'Debug.Print "max = " & CStr(IntMax)
'Debug.Print "Maximum indices are " & adr_i & "," & adr_j & "," & adr_k
End Sub
結果:
TestArrMaxMin
25,67969 max_in_array Loops=100
31,46484 max_in_array_of_array Loops=100
21,24609 max_in_array_each_in Loops=100