Alex Rivera | Logout

Performance difference between IIf() and If

Asked 2008-08-26T15:29:45.907
102

In Visual Basic, is there a performance difference when using the IIf function instead of the If statement?

Edit
Report

1 Answer

75

IIf() runs both the true and false code. For simple things like numeric assignment, this isn't a big deal. But for code that requires any sort of processing, you're wasting cycles running the condition that doesn't match, and possibly causing side effects.

Code illustration:

Module Module1
    Sub Main()
        Dim test As Boolean = False
        Dim result As String = IIf(test, Foo(), Bar())
    End Sub

    Public Function Foo() As String
        Console.WriteLine("Foo!")
        Return "Foo"
    End Function

    Public Function Bar() As String
        Console.WriteLine("Bar!")
        Return "Bar"
    End Function
End Module

Outputs:

Foo!
Bar!
answered 2008-08-26T15:40:29.703

Your Answer