0

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
  • 2
    You will want to read Description of "short-circuit" evaluation in Visual Basic
    – user40980
    Commented Feb 6, 2014 at 20:52
  • the three examples are not equivalent; the first one returns false when ClassA.num != ClassB.num OR ClassA.str != ClassB.str Commented Feb 6, 2014 at 22:39
  • Rule 1) of Optimization - You Can not tell without profiling. My experience of optimizers is that usually they do a much better job than me at this kind of stuff.
    – mattnz
    Commented Feb 7, 2014 at 2:12
  • @Wayne: now the third snippet doesn't match the other two ;) Commented Feb 11, 2014 at 16:57
  • @Steven: Okay... this time they should all match (if anyone was wondering: the first snippet was how I wrote my original code, but I changed it to the second snippet using OrElse statements)
    – Wayne
    Commented Feb 11, 2014 at 17:58

1 Answer 1

3

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
  • 2
    Most of my schooling was in C# so I did not know that in VB.Net using And / Or was not short-circuiting.
    – Wayne
    Commented Feb 6, 2014 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.