Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is it more expensive to create an object, or get the objects value?

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!

like image 923
K-RAN Avatar asked Dec 01 '22 10:12

K-RAN


2 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;
}
like image 144
Peter Lawrey Avatar answered Dec 02 '22 22:12

Peter Lawrey


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.

like image 40
Bozho Avatar answered Dec 02 '22 22:12

Bozho