Search code examples
javajvmheap-memorydalvikstack-memory

In Java, can operations on object fields bypass the stack?


Java heap only stores objects, and stack only stores primitive data and object reference.

Consider A.a = B.b , where A.a and B.b are int.

In my understanding, a JVM will first GET the value of A.a from the heap to the stack, and then PUT the value to B.b which is on the heap. It seems that the only way to change data on heap is to PUT the value from the stack.

My question is: is there some way to operate data on Java heap without stack? E.g., copy the value of A.a direct to B.b without stack operation.

If you say "it depends on the implementation of JVM", then my question is about Dalvik.


Solution

  • When considering JIT, things get complicated. I think my question is actually about Java compiler, not JVM

    If you are thinking of the javac you should assume that it does almost no optimisation and gives in byte code almost a literal translation of the code, which is very stack based.

    In fact the byte code will be using the stack more than your example suggests. It does operations like

    push B
    getAndPushField b
    push A
    popAndSetField a
    

    i.e. instead of one stack operation, there is notionally 3.

    The JIT on the other hand might optimise this away so it is not even using a register for the value. Depending on the processor

    // R3 contains A, R7 contains B, 
    // a starts at the 14th byte
    // b start at the 16th byte
    MOVI [R3+14], [R7+16]