Just a simple question and I was wondering is anyone had any insight into this.
If you are using lots of if-Elses or, lots of select cases - which would be faster.
Cheers,
RyanJ
Printable View
Just a simple question and I was wondering is anyone had any insight into this.
If you are using lots of if-Elses or, lots of select cases - which would be faster.
Cheers,
RyanJ
I have heard valid arguments (and proof) for both being faster than the other, based on the situation in which they are used. Neither one is so much faster that there is an obvious choice without trying it out.
Unless the code needs to be run at the fastest speed possible I would recommend just using whichever seems more appropriate at the time (based on the circumstances, your style, and which is easiest to read).
If speed really matters then you should look into the structure of your code rather than just the actual language constructs that you implement it with. For example, due to the way that conditions are evaluated when they contain boolean And operators it can be much more efficient to use two If's instead (assuming that one of the conditions is used for another If), eg:
is more efficient like this:VB Code:
If (A And C) Then 'do this ElseIf (B) Then 'do that ElseIf (C) Then 'do something else Else.... End If
It isn't always possible to arrange repeated conditions in a collection of Ifs in a way like this, so it is worth considering putting the result of a calculation into a variable, then using the variable in the If's (but bear in mind this could be bad for speed as well as good).VB Code:
If (C) Then If (A) Then 'do this (same number of conditions evaluated as before) Else 'do something else (one less condition evaluated) End If ElseIf (B) Then 'do that (one less condition evaluated) Else.... '(two less conditions evaluated) End If
There are several useful tips (including one for Ifs/Select Cases) in this optimisation thread: http://www.vbforums.com/showthread.php?t=315632
Ah, Right I see - thank you for the information si_the_geek :)
Also, thanks for the thread link that should prove most useful!
Cheers,
RyanJ
Actually I proved that If...ElseIf is faster than Select...Case in another thread (can't remember which one though). I think it won on both IDE mode and EXE mode. Even had the performance test uploaded in there. Try searching for "If Then" and see if you can find it. I think |2eM!x started that thread.
Quote:
Originally Posted by Jacob Roman
Ok, Will do :)
Cheers,
RyanJ