Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select case over IF

Status
Not open for further replies.

thomasmcgeown

Technical User
Feb 6, 2002
27
GB
In terms of speed, is it better to use select case or a series of IF statements?

If anyone can explain why one is quicker than the other (if it is) id appreciate it :)

Cheers
 
i would guess if you had one CASE statement than the IF statement would be quicker.
where the cross over occurs ie select case becomes quicker i couldnt say.(thats if it every does)

isnt the main advantage making your code easier to read and maintain?

regards,
vonmoyla
 
Select case is probably marginally faster because the compiler has a single value to compare on each Case clause. An "If" can of course evaluate completely different values in each successive "ElseIf" clause.

I agree with MrMovie however ... I doubt that the speed differences are much and the decision is usually about readability and maintainability rather than speed.
 
Put 2 buttons on the form, copy and paste this code and you will see the difference at the form's caption after clicking the buttons (just wait for up to a minute).

Option Explicit

Private Sub Command1_Click()
Dim i As Long
Dim a, b, c, d, e, f, g, h
Dim myStart As Date
Dim myEnd As Date

myStart = Now
For i = 0 To 99999999

If a = b Then

ElseIf a = c Then

ElseIf a = d Then

ElseIf a = e Then

ElseIf a = f Then

ElseIf a = g Then

ElseIf a = h Then

End If

Next i
myEnd = Now

Caption = DateDiff("s", myStart, myEnd)

End Sub

Private Sub Command2_Click()
Dim i As Long
Dim a, b, c, d, e, f, g, h
Dim myStart As Date
Dim myEnd As Date

myStart = Now
For i = 0 To 99999999

Select Case True
Case a = b

Case a = c

Case a = d

Case a = e

Case a = f

Case a = g

Case a = h

Case Else

End Select
Next i
myEnd = Now

Caption = DateDiff("s", myStart, myEnd)
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top