I am using a function to compare over 100 variables inside of classes to each other an am curious if one method of comparing multiple condition statements is more efficient than another. I am currently considering one of these methods. I think the ‘single If using And/Or’ looks the cleanest but performance is more important. (my code is VB.Net)
Multiple ElseIf
If Not ClassA.num = ClassB.num Then
Return False
ElseIf Not ClassA.str = ClassB.str Then
Return False
Else : Return True
End If
Single If using And/Or
If Not ClassA.num = ClassB.num Or
Not ClassA.str = ClassB.str Then
Return False
Else : Return True
End If
Nested If
If ClassA.num = ClassB.num Then
If ClassA.str = ClassB.str Then
Return True
End If
End If
Return False
Edit: Changed second code snippet from And to Or
Edit 2: Changed third snippet from If Not to If
5
I don’t think it gets any more efficient than short-circuit evaluation for real trivial chains like this:
Return ClassA.intVariable = ClassB.intVariable AndAlso ClassA.longVariable = _
ClassB.longVariable AndAlso ClassA.str = ClassB.str
Notice how AndAlso
is used, not And
. Also shorter, quicker-to-compare stuff is mentioned (and evaluated) first, with longer, slower-to-compare stuff further in the back.
1