I ran the following test to determine the difference in efficiency between IIf
and Abs
:
Public Sub TestSpeed()
Dim i As Long
Dim res As Integer
Debug.Print "*** IIF ***"
Debug.Print Format(Now, "HH:mm:ss")
For i = 1 To 999999999
res = IIf(-1 = True, 1, 0)
Next
Debug.Print Format(Now, "HH:mm:ss")
Debug.Print "*** ABS **"
Debug.Print Format(Now, "HH:mm:ss")
For i = 1 To 999999999
res = Abs(-1)
Next
Debug.Print Format(Now, "HH:mm:ss")
End Sub
The results show that Abs
is about 12 times faster:
TestSpeed
*** IIF ***
15:59:08
16:01:26
*** ABS **
16:01:26
16:01:37
Can anyone support this or prove that the contrary is true?
EDIT:
One situation in which one may need to decide between the two functions is for doing multiple counts based on criteria in an SQL query such as:
SELECT Sum(Abs(Colour = 'Yellow')) AS CountOfYellowItems, Sum(Abs(Votes>3) AS CountOfMoreThanThreeVotes FROM tblItems
versus
SELECT Sum(IIf(Colour = 'Yellow' ,1 ,0)) AS CountOfYellowItems, Sum(IIf(Votes > 3 ,1 ,0) AS CountOfMoreThanThreeVotes FROM tblItems