So say for example I'm going through an 'if' block and in this block, I am comparing the value of some number to a constant. Would it be more expensive like this:
if( foo.getOb().getVal() == CONST_0 )
{
....
}
....
if( foo.getOb().getVal() == _CONST_N )
{
....
}
else
....
OR:
int x = foo.getOb().getVal();
if( x == CONST_0 )
{
....
}
....
if( x == _CONST_N )
{
....
}
else
....
I know that this may seem like a stupid question. I think that the second implementation is fast/more efficient but I'm curious as to why. I've been trying to think of the reason for the last couple of minutes and can't really come up with anything since my knowledge on Java is...a bit lacking.
Thanks a lot for any answers!
It looks to me that you should be using a switch statement, in which case, you don't need to worry about it.
switch (foo.getOb().getVal()) {
case CONST_0:
....
break;
case CONST_N:
....
break;
default:
....
break;
}
This is not object creation. You are creating a reference to the object.
You are saving a few method-calls (in Java they are very efficient)
The difference is negligible. And It is not unlikely that the compiler will optimize such things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With