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!


在我看来,你应该使用switch语句,在这种情况下,你不需要担心它。

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.


Assuming getOb() and getVal() simply return references and don't do calculations, then these two snippets of code are functionally equivalent. Meaning that there is no real discernible difference between them.

Debating between which form to use comes down to a question of style and preference, and borders on pre-emptive optimization (in that you may spend a lot of time arguing about making a change which has zero measurable impact on your application's performance).

链接地址: http://www.djcxy.com/p/39582.html

上一篇: VS2008 c ++编译器会优化下面的if语句吗?

下一篇: 在Java中,创建对象或获取对象值会更昂贵吗?