The dup instruction simply duplicates the top element of the operand stack. If the compiler knows that it will use the value several times over a relatively short period of time, it can choose to duplicate the value and hold it on the operand stack until it is needed.
One of the most common cases when you see dup is when you create an object and save it in a variable:
Foo foo = new Foo();
Running javap -c will give you the following bytecode:
0: new
In English: the new operation creates a new instance of the Foo object, and invokespecial executes the Foo constructor. Since you need a link in the stack to call the constructor, as well as to store in a variable, it makes sense to use dup (especially since the alternative, storing in a variable and then retrieving to start ctor may violate the Java memory model).
Here is the case where Oracle Java Compiler (1.6) did not use dup when I would expect this:
int x = 12; public int bar(int z) { int y = x + x * 3; return y + z; }
I expect the compiler to be a dup value of x , as it appears several times in the expression. Instead, enter the code that reloaded the value from the object:
0: aload_0 1: getfield
I would expect dup , because it is relatively expensive to get the value from the object (even after Hotspot does its magic), whereas two stack cells are likely to be on the same cache line.
parsifal
source share