4

Is there a performance advantage to using IIf over If?

Other than simply less code... what is the difference between :

If msInitialFloodSection <> Trim$(cboFloodSection.Text) Then
    mbFloodSectionChanged = True
Else
    mbFloodSectionChanged = False
End If

and

mbFloodSectionChanged = IIf(msInitialFloodSection <> Trim$(cboFloodSection.Text), True, False)
aserwin
  • 1,040
  • 2
  • 16
  • 34

1 Answers1

16

IIf is not an operator or a language construct, it's a function, just like any other function such as Left. It will therefore evaluate all its arguments at all times, whereas with If you will only evaluate the correct branch.

Example:

denominator = 0
value = IIf(denominator = 0, 0, value / denominator)

This will raise Divizion by zero error despite a separate branch exists for denominator being zero.

Regarding performance, what it will do is packing your values into Variants which will require additional ticks, not that much at all, but if we're on performance, then If will be faster because it wouldn't coerce things through Variants and because it will only calculate one of the values, not two.

GSerg
  • 76,472
  • 17
  • 159
  • 346
  • That is what I was wondering... I know there is no "short circuiting" in VB6, but I was worried that maybe `IIf` was sort of counter productive! Seems to be so? – aserwin Oct 24 '12 at 13:58
  • 4
    @aserwin Sort of yes; I wouldn't call it from a tight loop. But for trivial one-time assignments like the one you're showing in the question I tend to use `IIf` because it looks nicer, and the performance penalty is almost non-existant. – GSerg Oct 24 '12 at 14:07