0
我有3個不同的變量,所有3可以有2個不同的值。每個組合都需要做其他事情。我可以把它全部放入IF聲明中,但我想知道是否沒有更優雅/適當/更短的解決方案。 3個變量的值可以是1或0(如二元真值表)。IF語句或更有效的東西?
我有3個不同的變量,所有3可以有2個不同的值。每個組合都需要做其他事情。我可以把它全部放入IF聲明中,但我想知道是否沒有更優雅/適當/更短的解決方案。 3個變量的值可以是1或0(如二元真值表)。IF語句或更有效的東西?
雖然它不是二進制分支不嚴格更高效(除非你能預測的參數的頻率),一個選擇是使用VBA的語法的特點,並把它放在一個Select Case
結構:
Private Sub Example(one As Boolean, two As Boolean, three As Boolean)
Select Case True
Case one And Not two And Not three
Debug.Print "Case 1"
Case one And Not two And three
Debug.Print "Case 2"
Case one And two And Not three
Debug.Print "Case 3"
Case one And two And three
Debug.Print "Case 4"
Case two And Not three
Debug.Print "Case 5"
Case two And three
Debug.Print "Case 6"
Case three
Debug.Print "Case 7"
Case Else
Debug.Print "Case 8"
End Select
End Sub
這當然更容易看比如果選擇:
Private Sub Example2(one As Boolean, two As Boolean, three As Boolean)
If one Then
If two Then
If three Then
Debug.Print "Case 4"
Else
Debug.Print "Case 3"
End If
Else
If three Then
Debug.Print "Case 2"
Else
Debug.Print "Case 1"
End If
End If
Else
If two Then
If three Then
Debug.Print "Case 6"
Else
Debug.Print "Case 5"
End If
Else
If three Then
Debug.Print "Case 7"
Else
Debug.Print "Case 8"
End If
End If
End If
End Sub
當我對最壞情況的基準(獨立運行,每次結算之間的直接窗口)個在一百萬次迭代中,性能差異僅在20ms左右。絕大多數性能提升將來自於確定訂單您評估變量 - 也就是哪些分支更有可能。
嵌套if語句是處理此決策樹的最有效方式。 – Mangist
https://support.office.com/zh-cn/article/IIf-Function-32436ecf-c629-48a3-9900-647539c764e3 – Vasily
到目前爲止,您已經測試過什麼? –