Jul 13th, 2006, 07:41 AM
Classic VB - I want to use IIf but it is slow!
IIf is somewhat handy for shortening your code, but it is awfully slow: it takes Variants and outputs a Variant, which are very slow.
There is also another problem: when you give a the TruePart and FalsePart to IIf, both of these code snippets are executed. This doesn't happen with If ... Then ... Else. If you wish to test this claim, here is a quick sample:
Private Sub Form_Load()
' you will see both messageboxes and the return value of the button you chose in the first messagebox
MsgBox IIf(True, MsgBox("Oh!", vbRetryCancel), MsgBox("I didn't know this!", vbYesNo))
Thankfully, there is a solution to the Variant problem! Make your own IIf replacement for the specific datatype you are about to use. This can be an order of magnitude faster than IIf! In my own quick testing, while IIf took 2500 ms the custom IfLng function took only 60 ms when I called them ten million times!
Place these into their own module and enjoy:
Public Function IfByte(ByVal Expression As Boolean, ByVal TruePart As Byte, ByVal FalsePart As Byte) As Byte
If Expression Then IfByte = TruePart Else IfByte = FalsePart
Public Function IfInt(ByVal Expression As Boolean, ByVal TruePart As Integer, ByVal FalsePart As Integer) As Integer
If Expression Then IfInt = TruePart Else IfInt = FalsePart
Public Function IfLng(ByVal Expression As Boolean, ByVal TruePart As Long, ByVal FalsePart As Long) As Long
If Expression Then IfLng = TruePart Else IfLng = FalsePart
Public Function IfVar(ByVal Expression As Boolean, ByVal TruePart As Variant, ByVal FalsePart As Variant) As Variant
If Expression Then IfVar = TruePart Else IfVar = FalsePart
You can create your own for Date, Currency, Double, Single, any object... they all will be faster than IIf. Actually, even IfVar is twice faster than IIf. Don't ask me how, it just is. Despite being as useful as IIf.
Last edited by Merri; Aug 8th, 2006 at 02:06 AM.
Click Here to Expand Forum to Full Width