简体   繁体   中英

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.

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.)

Your code does include some additional computations from compiler point of view. Need to allocate memory for booleans(that ur returning) and do a >b computation. A>b returns Boolean so if u return that it is easy. They both have same from logic though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM