Reputation: 5087
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.
Upvotes: 5
Views: 6737
Reputation: 280102
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.)
Upvotes: 8
Reputation: 316
Your code does include some additional computations from compiler point of view. Need to allocate memory for booleans(that u r 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.
Upvotes: 0