Results 1 to 1 of 1
  1. #1

    Thread Starter
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002

    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:
    VB Code:
    1. Private Sub Form_Load()
    2.     ' you will see both messageboxes and the return value of the button you chose in the first messagebox
    3.     MsgBox IIf(True, MsgBox("Oh!", vbRetryCancel), MsgBox("I didn't know this!", vbYesNo))
    4. End Sub

    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:
    VB Code:
    1. Public Function IfByte(ByVal Expression As Boolean, ByVal TruePart As Byte, ByVal FalsePart As Byte) As Byte
    2.     If Expression Then IfByte = TruePart Else IfByte = FalsePart
    3. End Function
    4. Public Function IfInt(ByVal Expression As Boolean, ByVal TruePart As Integer, ByVal FalsePart As Integer) As Integer
    5.     If Expression Then IfInt = TruePart Else IfInt = FalsePart
    6. End Function
    7. Public Function IfLng(ByVal Expression As Boolean, ByVal TruePart As Long, ByVal FalsePart As Long) As Long
    8.     If Expression Then IfLng = TruePart Else IfLng = FalsePart
    9. End Function
    10. Public Function IfVar(ByVal Expression As Boolean, ByVal TruePart As Variant, ByVal FalsePart As Variant) As Variant
    11.     If Expression Then IfVar = TruePart Else IfVar = FalsePart
    12. End Function

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts


Click Here to Expand Forum to Full Width

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.