1

I have a basic doubt regarding object creation in java.Suppose i have two classes as follows

Class B{  
    public int value=100;  
}

Class A{  
    public B getB(){  
        return new B();  
    }  
    public void accessValue(){
        //accessing the value without storing object B
        System.out.println("value is :"+getB().value);

        //accessing the value by storing object B in variable b       
        B b=getB();
        System.out.println("value is :"+b.value);

   }  
}

My question is,does storing the object and accessing the value make any difference in terms of memory or both are same?

7
  • Have a look at the generated byte code... Commented Dec 8, 2011 at 12:18
  • 1
    The code doesn't even compile, please elaborate. Commented Dec 8, 2011 at 12:19
  • @JoonasPulakka: It does if you put the classes in separate files. I think the OP combined his code for simplicity. Commented Dec 8, 2011 at 12:20
  • There is a little bit of information here about how local variables are stored if you are interested: java.sun.com/docs/books/jvms/second_edition/html/… Commented Dec 8, 2011 at 12:20
  • @Joonas:Ok well.There are two approach to access "value".1) get an object of B and store it in a variable b and then access the data member "value". 2)get an object of B using getB() and directly access "value".My question is whether both 1 and 2 are same in terms of memory efficiency. Commented Dec 8, 2011 at 12:24

7 Answers 7

3

They are both equivalent, since you are instantiating B both times. The first way is just a shorter version of the second.

Sign up to request clarification or add additional context in comments.

Comments

2

Following piece of code is using an anonymous object. which can't be reused later in code.

//accessing the value without storing object B     
System.out.println("value is :"+getB().value); 

Below code uses the object by assigning it to a reference.

//accessing the value by storing object B in variable b             
B b=getB();      
System.out.println("value is :"+b.value); 

Memory and performance wise it's NOT much difference except that in later version stack frame has an extra pointer.

3 Comments

Minor addition: I believe the anonymous object also goes out of scope (and so becomes available for garbage collection) straight away.
Yes, agree! As no reference is attached to it. it must be sweeped in next GC run.
Though, as a practical matter, in a method this small the b will be out of scope only microseconds after the anonymous object.
1

It is the same. This way: B b=getB(); just keeps your code more readable. Keep in mind, that object must be stored somewhere in memory anyway.

1 Comment

Actually, at the bytecode level, in the first version the value is held in the "stack", and never "stored". But that's just a conceptual distinction, of course, as the stack location and "storage" location would only be separated by maybe 20 bytes in memory. And, once JITCed, the value would be held in register in both cases.
1

If you never reuse the B-object after this part, the first option with an anonymous object is probably neater:

  • the second option would need an additional store/load command (as Hot Licks mentioned) if it isn't optimized by the compiler
  • possibly first storing the object in a variable creates slight overhead for the garbage collector as opposed to an anonymous object, but that's more of a "look into that" than a definitive statement of me
  • If you do want to access a B a second time, storing one in its own variable is faster.

    EDIT: ah, both points already mentioned above while I was typing.

    Comments

    0

    You will not be able to say the difference without looking at the generated machine code. It could be that the JIT puts the local variable "b" onto the stack. More likely however that the JIT will optimize b away. Depends on the JRE and JIT you are using. In any case, the difference is minor and only significant in extremely special cases.

    1 Comment

    To preserve side-effect order the JITC can't "optimize away" b, but it can hold it in a register, making the logic essentially identical in both cases.
    0

    Actually there is no difference in the second instance you are just giving the new object reference to b.

    So code wise you cannot achieve the println if you use version 1, as you dont have any reference as you have in the second case unless you keep creating new object for every method call.

    5 Comments

    The println will work as well in the first case as it would in the second.
    how without creating a new object ?
    It will, of course, create a new object, in the called method getB. It's a separate call.
    so does it make sense to keep on creating a new object just to call a method, thats what my answer is
    No, but this is a toy example.
    0

    In that case the difference, if any, would not be worth mentioning. In the second case an extra bytecode or two would probably be generated, if the compiler didn't optimize them away, but any decent JIT would almost certainly optimize the two cases to the identical machine code.

    And, in any event, the cost of an extra store/load would be inconsequential for 99.9% of applications (and swamped in this case by the new operation).

    Details: If you look at the bytecodes, in the first case the getB method is called and returns a value on the top of the stack. Then a getfield references value and places that on the top of the stack. Then a StringBuilder append is done to begin building the println parameter list.

    In the second case there is an extra astore and aload (pointer store/load) after the getB invocation, and the setup for the StringBuilder is stuck between the two, so that side-effects occur in the order specified in the source. If there were no side-effects to worry about the compiler might have chosen to do the very slightly more efficient dupe and astore sequence. In any case, a decent JIT would recognize that b is never used again and optimize away the store.

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.