Java: How will JVM optimise the call to a void and empty function?

前端 未结 6 918
囚心锁ツ
囚心锁ツ 2020-12-15 23:35

Let\'s imagine we have the following classes:

public class Message extends Object {}

public class Logger implements ILogger {
 public void log(Message m) {/         


        
6条回答
  •  甜味超标
    2020-12-16 00:03

    Disassembling the following file (with javap -c) suggests they are not stripped out by the 1.7.0 compiler when compiling down to bytecode:

    public class Program
    {
        public static class Message extends Object {}
    
        public interface ILogger {
            void log(Message m);
        }
    
        public static class Logger implements ILogger {
            public void log(Message m) { /* empty */ }
        }
    
        public static void main(String[] args) {
            ILogger l = new Logger();
            l.log((Message)null); // a)
            l.log(new Message()); // b)
        }
    }
    

    The result is below. The key bits are the invokes on lines 13 and 26.

    Compiled from "Program.java"
    public class Program {
      public Program();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."":()V
           4: return
    
      public static void main(java.lang.String[]);
        Code:
           0: new           #2                  // class Program$Logger
           3: dup
           4: invokespecial #3                  // Method Program$Logger."":()V
           7: astore_1
           8: aload_1
           9: aconst_null
          10: checkcast     #4                  // class Program$Message
          13: invokeinterface #5,  2            // InterfaceMethod Program$ILogger.log:(LProgram$Message;)V
          18: aload_1
          19: new           #4                  // class Program$Message
          22: dup
          23: invokespecial #6                  // Method Program$Message."":()V
          26: invokeinterface #5,  2            // InterfaceMethod Program$ILogger.log:(LProgram$Message;)V
          31: return
    }
    

    EDIT: However, as @mikera pointed out, it's likely that the JIT compiler will do further optimizations when the program runs, which may be able to eliminate the calls. I don't know enough about the details to comment on that unfortunately.

    SIDE NOTE: You might be interested in this link, which deals with performance techniques used by the Hotspot JVM:

    https://wikis.oracle.com/display/HotSpotInternals/PerformanceTechniques

提交回复
热议问题