Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Byte Code ordering of this and parameters on the stack

In java bytecode why is the receiver is pushed onto the stack first followed by all the parameters? I seem to remember it being something to do with efficiency.

This is true for both method calls and setting fields.

Method Call

class X {

    int p(int a) {
        //Do something
    }
    int main() {
        int ret = p(1);
    }

}

Main method compiles to:

aload_0 // Load this onto the stack
iconst_1 // Load constant 1 onto the stack
invokevirtual <int p(int)> from class X

Setting a field:

class X {
    int x;
    int main() {
        x = 1;
    }

}

Main method compiles to:

aload_0 // Load this onto the stack
iconst_1 // Load constant 1 onto the stack
putfield <int x> from class X
like image 851
Jonathan Evans Avatar asked May 12 '12 17:05

Jonathan Evans


2 Answers

Being pushed first has advantages in that

  • The target method can use the denser "aload0" bytecode (smaller than if it were much later in the parameter list and had to use a parametric version of the aload bytecode. Because "this" is often referenced in methods for both field and method access, it leads to a real code density improvement.
  • One often does cascading method sends like "foo.bar().baz()". When bar() returns, the future "this" for .baz() is magically already in the right place on the stack if you arrange things as was done in Java.
like image 96
Trent Gray-Donald Avatar answered Sep 29 '22 11:09

Trent Gray-Donald


Are you asking why it is pushed at all? In both cases you're accessing something that belongs to an instance of the class, so this has to be part of that process.

Are you asking why it is pushed first? Just Java convention. I guess it's convenient to always have this first regardless of the many things that could follow.

like image 37
Sean Owen Avatar answered Sep 29 '22 10:09

Sean Owen