Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCompare the speeds of IIf and If Then statements
KeywordsIIf, If Then, speed, performance
CategoriesSoftware Engineering, Tips and Tricks
 
When you click Go, the program runs timed loops comparing IIf and If Then. In my tests, IIf takes more than 6 times as long as If Then!

IIf is also harder to read. Most of the cost of a large project is in debugging and maintenance so anything that causes extra confusion is bad.

 
Private Sub cmdGo_Click()
Dim num_trials As Long
Dim i As Long
Dim start_time As Single
Dim stop_time As Single
Dim x As Integer

    num_trials = CLng(txtNumTrials.Text)
    lblIfThen.Caption = ""
    lblIIf.Caption = ""
    Screen.MousePointer = vbHourglass
    DoEvents

    start_time = Timer
    For i = 1 To num_trials
        If i = 0 Then
            x = 1
        Else
            x = 2
        End If
    Next i
    stop_time = Timer
    lblIfThen.Caption = Format$(stop_time - start_time, _
        "0.0000") & " seconds"
    DoEvents

    start_time = Timer
    For i = 1 To num_trials
        x = IIf(i = 0, 1, 2)
    Next i
    stop_time = Timer
    lblIIF.Caption = Format$(stop_time - start_time, _
        "0.0000") & " seconds"

    Screen.MousePointer = vbDefault
End Sub
 
My book Bug Proofing Visual Basic gives lots of other tips for reducing the number of bugs in a Visual Basic program.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated