» 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!

IIf vs. If...Then

Using IIf certainly is slower than the normal "If...Then" clause. Should I add more? Well, anyway, here's the code:

Code:
Public Sub TestOne() Dim intRnd As Integer Dim blnReturn As Boolean intRnd = CInt(Rnd(1)) Call IIf(intRnd = 0, blnReturn = True, blnReturn = False) End Sub Public Sub TestTwo() Dim intRnd As Integer Dim blnReturn As Boolean intRnd = CInt(Rnd(1)) If intRnd = 0 Then blnReturn = True Else blnReturn = False End If End Sub

IIf % faster than If...Then IIf (sec) If...Then (sec)
77,6% 1,075868 0,605669
68% 1,066235 0,634840
78,3% 1,071904 0,601049
84,5% 1,079631 0,585207
88,3% 1,108866 0,588789


User contributed notes:

Author: VBBR () Date: 19:03 28/03/2004
And there is the other way to use IIf...

return = IIf(expression,IfIsTrue,IfIsFalse)

The IIf function evaluates "expression". If it is True then "return" will be set equal to "IfIsTrue". If "expression" is False, "return" will be set to "IfIsFalse".

Author: Tom (hurendo_kun at hotmail dot com) Date: 15:05 31/05/2005
When using IIf, bear in mind that EVERY expression in the statement is evaluated, whether the condition evaluates to True or not. For this reason, unless you absolutely need IIf to keep your code clean, you should stick with If..Then for speed.

Author: Almar () Date: 19:05 31/05/2005
Thanks for pointing that one out!

Author: Merri () Date: 22:07 15/07/2006
You can create custom IIf for specific datatypes; actually, even custom IfVar (for Variants) is twice faster than the native IIf!

[code]
Public Function IfVar(ByVal Expression As Boolean, ByRef TruePart As Variant, ByRef FalsePart As Variant) As Variant
If Expression Then IfVar = TruePart Else IfVar = FalsePart
End Function
[/code]

Author: Pop! (piranaface at hotmail dot com) Date: 22:09 15/09/2006
In the test, this line is definitely wrong:
Call IIf(intRnd = 0, blnReturn = True, blnReturn = False)

As VBBR pointed out, IfIsTrue and IfIsFalse are both evaluated. Assuming blnReturn starts out False, "blnReturn = True" will evaluate to False and "blnReturn = False" evaluates to True. These two unintentional comparisons were not performed in the If/Then test, which may account for the speed difference.

What's more, by using Call IIf() instead of blnReturn = IIf() you are discarding the returned value. Oops.

For the purpose of the test, I recommend changing that line to:
blnReturn = IIf(intRnd = 0, True, False)

Author: Pop! (piranaface at hotmail dot com) Date: 22:09 16/09/2006
Whoops! I meant "As Tom pointed out..."

Why is it that whenever I criticise someone else's mistakes, I end up making my own?

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