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

前端 未结 6 917
囚心锁ツ
囚心锁ツ 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:06

    It is impossible to say definitively - it will depend on the implementation of the JVM / Java compiler.

    A smart enough compiler can prove that neither statements have an effect, and can therefore eliminate them. I believe most modern JVMs will do this, though you would need to test on your specific configuration to be sure.

    a) is easier to optimise away than b) since b) includes a constructor call, which the compiler also needs to prove has no side effects before it can optimise away the whole statement.

    Note that you'd expect this kind of elimination to be done by the JIT compiler rather than the Java compiler itself, i.e. bytecode would probably be generated that included the log function calls, but this is later optimised away by the JIT compiler when it compiles down to native code.

    Also, since the JIT can recompile on runtime statistics etc., it is possible that the code will be there to start with, but get compiled away later on successive optimisations.

提交回复
热议问题