Some time ago, I was engaged in a project. The project included generating JVM byte code to process some data. And I discovered some limitations of JVM Hotspot.
There are two versions of a task.
The first version:
public static final XXX.Seq apply(XXX.Seq);
Code:
0: aload_0
1: invokevirtual #13 // Method XXX/Seq.iterator:()LXXX/Iterator;
4: astore_1
5: invokestatic #19 // Method XXX/SimpleBuffer.create:()LXXX/SimpleBuffer;
8: goto 32
11: dup
12: aload_1
13: invokeinterface #25, 1 // InterfaceMethod XXX/Iterator.next:()Ljava/lang/Object;
18: checkcast #27 // class java/math/BigInteger
21: astore_2
22: aload_2
23: getstatic #33 // Field XXX/Literals.f2:Ljava/math/BigInteger;
26: invokestatic #38 // Method XXX/sumInt.apply:(Ljava/math/BigInteger;Ljava/math/BigInteger;)Ljava/math/BigInteger;
29: invokevirtual #42 // Method XXX/SimpleBuffer.add:(Ljava/lang/Object;)V
32: aload_1
33: invokeinterface #46, 1 // InterfaceMethod XXX/Iterator.hasNext:()Z
38: ifne 11
41: invokevirtual #50 // Method XXX/SimpleBuffer.toSeq:()LXXX/Seq;
44: areturn
The second version:
public static final XXX.Seq apply(XXX.Seq);
Code:
0: aload_0
1: invokevirtual #13 // Method XXX/Seq.iterator:()LXXX/Iterator;
4: astore_1
5: invokestatic #19 // Method XXX/SimpleBuffer.create:()LXXX/SimpleBuffer;
8: astore_3
9: goto 33
12: aload_3
13: aload_1
14: invokeinterface #25, 1 // InterfaceMethod XXX/Iterator.next:()Ljava/lang/Object;
19: checkcast #27 // class java/math/BigInteger
22: astore_2
23: aload_2
24: getstatic #33 // Field XXX/Literals.f2:Ljava/math/BigInteger;
27: invokestatic #38 // Method XXX/sumInt.apply:(Ljava/math/BigInteger;Ljava/math/BigInteger;)Ljava/math/BigInteger;
30: invokevirtual #42 // Method XXX/SimpleBuffer.add:(Ljava/lang/Object;)V
33: aload_1
34: invokeinterface #46, 1 // InterfaceMethod XXX/Iterator.hasNext:()Z
39: ifne 12
42: aload_3
43: invokevirtual #50 // Method XXX/SimpleBuffer.toSeq:()LXXX/Seq;
46: areturn
They have the same semantics. Each version iterates the source sequence and builds a new one (using a buffer). But the first version uses the operand stack to intermediately store the buffer (with the
dup instruction). The second version uses a local variable (with the astore_3 and aload_3 instructions) for the same purpose.In practice, the second version is much faster (about 3-4x times). I tested different JDKs (8-21) and got the same difference.
However, switching to the interpreter causes both versions to run at the same speed. This means the first version is not natural for HotSpot, which is oriented for the Java language.
So, don't be so smart with the operand stack, and prefer to use local variables when generating byte code.






















































