» Home » VB Fibre
Site
News
Files

Visual Basic
Strings
Math
General
Properties
Memory
Methods

Search
Testing

Inline ASM-VB
Strings
Math
General
Memory

Search
Using inline ASM
Submit!

Select Case vs If Then

The difference is really minimal. Practically, you wouldn't notice it I think. The difference is too small and/or can be caused by a background process... Because the code below has been called 500.000 times, and that 5 times... one major thing:It could be the "rnd" statement. But still the difference will be unnoticable

Code:
Public Sub TestOne() Dim intRND As Integer intRND = CInt(Rnd * 10) If intRND = 0 Then '//Do nothing ElseIf intRND = 1 Then '//Do nothing ElseIf intRND = 2 Then '//Do nothing ElseIf intRND = 3 Then '//Do nothing ElseIf intRND = 4 Then '//Do nothing Else '//Do nothing End If End Sub Public Sub TestTwo() Dim intRND As Integer intRND = CInt(Rnd * 10) Select Case intRND Case 0 '//Do nothing Case 1 '//Do nothing Case 2 '//Do nothing Case 3 '//Do nothing Case 4 '//Do nothing Case Else '//Do nothing End Select End Sub

If...Then % faster than Select Case If...Then (sec) Select Case (sec)
-2,9% 0,296791 0,305656
0,7% 0,303489 0,301407
1,5% 0,308557 0,304071
-5% 0,288757 0,303990
-1,1% 0,300547 0,303737


User contributed notes:

Author: grigri (grigri at spamdetector dot co dot uk) Date: 15:03 17/03/2004
What about if you declare intRND as a Long?

I believe that in that case the compiler creates a jump table rather than a series of conditionals, which is faster. I could be wrong though.

Author: Almar () Date: 12:03 20/03/2004
Hmm, I might try that. Never heard something about that, but there is still a lot to learn of VB :)

Author: Gregg Morrison (Gregg dot Morrison at GMRAD dot COM) Date: 21:08 21/08/2005
Where the SELECT CASE Statement really shines is when you have a *LOT* of cases. For example, consider the overhead of evaluating 64 or more separate IF-THEN-ELSEIF clauses when the TRUE clause is greater than 8. The SELECT CASE Statement really shines! I *Always* use SELCT CASE. Note that you can also use SELECT CASE to test a value against a dynamic Variable.

Add user-note
Author:
E-mail (optional):
Anti spam, please enter 'ok' without quotes:
Comment: