On Fri, 4 Oct 2024 12:05:02 GMT, Shaojin Wen <s...@openjdk.org> wrote:
> java.base should provide best practices for Class File API > > 1. Use fluent coding style > 2. Use aconst_null instead of oadConstant(null) > 3. use astore intead of 'storeLocal(REFERENCE' > 4. use aload instead of 'loadLocal(REFERENCE' > 5. 'lload/lstore' instead of 'loadLocal(LONG)/storeLocal(LONG)' Using a fluent coding style can reduce the code size, such as the following code import java.lang.classfile.CodeBuilder; public class Demo { public static void f0(CodeBuilder cb) { cb.aload(0); cb.aload(1); } public static void f1(CodeBuilder cb) { cb.aload(0) .aload(1); } } Compile Java code and view bytecode javac --enable-preview --release 24 Demo.java javap -c Demo The bytecode is as follows public class Demo { public Demo(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void f0(java.lang.classfile.CodeBuilder); Code: 0: aload_0 1: iconst_0 2: invokeinterface #7, 2 // InterfaceMethod java/lang/classfile/CodeBuilder.aload:(I)Ljava/lang/classfile/CodeBuilder; 7: pop 8: aload_0 9: iconst_1 10: invokeinterface #7, 2 // InterfaceMethod java/lang/classfile/CodeBuilder.aload:(I)Ljava/lang/classfile/CodeBuilder; 15: pop 16: return public static void f1(java.lang.classfile.CodeBuilder); Code: 0: aload_0 1: iconst_0 2: invokeinterface #7, 2 // InterfaceMethod java/lang/classfile/CodeBuilder.aload:(I)Ljava/lang/classfile/CodeBuilder; 7: iconst_1 8: invokeinterface #7, 2 // InterfaceMethod java/lang/classfile/CodeBuilder.aload:(I)Ljava/lang/classfile/CodeBuilder; 13: pop 14: return } We can see that method `f0` does not use the fluent code style, and the generated bytecode has redundant pop and aload_0 operations. ------------- PR Comment: https://git.openjdk.org/jdk/pull/21355#issuecomment-2393963891