Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant If statement warning

if ( a > b) {
  return true;
}
return false;

With the above code Netbeans gives "Redundant if statement" warning and suggest changing it to :

return a > b;

I think the first version is easier to read and prefer using it in my code. I want to know if there is any disadvantages of it compared to the suggested one.

like image 695
Salih Erikci Avatar asked Dec 01 '14 16:12

Salih Erikci


1 Answers

This

if ( a > b) {
  return true;
}
return false;

consists in pushing the value of a on the stack, pushing the value of b on the stack, popping both and checking the result of >. If it's true, push the value of true on the stack, then pop it and return it. If it's false, branch to further down in the bytecode, push the value of false on the stack, pop it and return.

In the case of

return a > b;

you're pushing the value of a and b on the stack, then popping the values and pushing the result of > on those values onto the stack. Then popping that value and returning it.

So

return a > b;

is unnoticeably more efficient at the byte code level.

(IMO I find the second more readable and I believe most will, too.)

like image 134
Sotirios Delimanolis Avatar answered Sep 28 '22 06:09

Sotirios Delimanolis