If, IIf() and If()

非 Y 不嫁゛ 提交于 2019-12-22 04:12:01

问题


I recently asked a question about IIf vs. If and found out that there is another function in VB called If which basically does the same thing as IIf but is a short-circuit.

Does this If function perform better than the IIf function? Does the If statement trump the If and IIf functions?


回答1:


Damn, I really thought you were talking about the operator all along. ;-) Anyway …

Does this If function perform better than the IIf function?

Definitely. Remember, it's built into the language. Only one of the two conditional arguments has to be evaluated, potentially saving a costly operation.

Does the If statement trump the If and IIf functions?

I think you can't compare the two because they do different things. If your code semantically performs an assignment you should emphasize this, instead of the decision-making. Use the If operator here instead of the statement. This is especially true if you can use it in the initialization of a variable because otherwise the variable will be default initialized, resulting in slower code:

Dim result = If(a > 0, Math.Sqrt(a), -1.0)

' versus

Dim result As Double ' Redundant default initialization!
If a > 0 Then
    result = Math.Sqrt(a)
Else
    result = -1
End If



回答2:


One very important distinct between IIf() and If() is that with Option Infer On the later will implicitly cast the results to the same data type in certain cases, as where IIf will return Object.

Example:

    Dim val As Integer = -1
    Dim iifVal As Object, ifVal As Object
    iifVal = IIf(val >= 0, val, Nothing)
    ifVal = If(val >= 0, val, Nothing)

Output:
iifVal has value of Nothing and type of Object
ifVal has value of 0 and type of Integer, b/c it is implicitly converting Nothing to an Integer.



来源:https://stackoverflow.com/questions/28478/if-iif-and-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!