Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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

share|improve this question
2  
You will want to read Description of "short-circuit" evaluation in Visual Basic –  MichaelT Feb 6 at 20:52
    
the three examples are not equivalent; the first one returns false when ClassA.num != ClassB.num OR ClassA.str != ClassB.str –  Steven A. Lowe Feb 6 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 Feb 7 at 2:12
    
@Wayne: now the third snippet doesn't match the other two ;) –  Steven A. Lowe Feb 11 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 Feb 11 at 17:58

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
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 Feb 6 at 21:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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