Will
Will

Reputation: 8651

two IF statements vs. one AND statement

Within java I wonder which of these is more efficient:

if(something)
   {
      if(something)
    }

or

if((something) &&(something))

I was wondering what the merits are for both in terms of performance. Which solutions lend themselves better to different data objects.

Upvotes: 15

Views: 36180

Answers (5)

Vinze
Vinze

Reputation: 2539

I don't know but, by intuition, I think that once compiled into bytecode there is no difference...

Upvotes: 0

Jesper
Jesper

Reputation: 207006

Note that the && operator in Java is a short circuit operator. That means that if the expression on the left side of the && is false, Java won't bother to evaluate the expresion on the right side, because the result of is going to be false, no matter what the right hand side expression evaluates to.

So, effectively, the performance of these two constructions will be the same.

Note that Java also has an & operator. That one does not short circuit: it will always evaluate the expressions on both sides of the &.

Upvotes: 2

Abbas
Abbas

Reputation: 14432

In general they are the same. If the first one is evaluated false, the second one will not be evaluated. In case you want something to happen if the first one is false, you should use the separate if-statement. Otherwise, if you only want to be sure both are true and do nothing if one of them return false, you can use the second option.

Upvotes: 2

NPE
NPE

Reputation: 500913

In Java, && short-circuits. This means that if the first condition in a && b evaluates to false, the second condition isn't even evaluated.

Therefore, the two almost certainly result in identical code, and there's no performance difference.

Of the two forms, you should use whichever results in clearer code.

Upvotes: 3

Kris
Kris

Reputation: 14468

Performance will be identical. The first statement will be evaluated and only if it is true will the second one be evaluated.

This is merely a question of readability. Unless there is something that needs to be done if the first statement is true, regardless of the second, I'd go with both in the same line as it is clearer that both statements need to be true for something to happen. You also don't have to indent unnecessarily.

Upvotes: 21

Related Questions