Java 最终 boolean 优化

标签 java optimization

考虑以下设置:

// debugger class
public class Debug
{
    // setting
    public final static boolean DEBUG = false;

    void print_checked( String s )
    {
        if( DEBUG )
            System.out.print( s );
    }

    void print_unchecked( String s )
    {
        System.out.print( s );
    }
}

// worker class
public class Algorithm
{
    Debug debugger;

    public void heavyWeightAlgorithmImplementation()
    {
        // method 1
        debugger.print_checked( "This method 1" );

        // method 2
        if( debugger.DEBUG )
            debugger.print_unchecked( "Or this method 2" );
    }
}

我已阅读here Java 中的final boolean很可能会被优化掉。然而,正如我的设置一样,if 条件位于另一个类中,并且当前在 print_checked() 中实现。 Java 是否也优化了函数调用(方法 1),还是我必须像方法 2 那样重写所有内容?

编辑#1:再次添加静态

最佳答案

我用jdk1.7编译了上面的例子,并在jd-gui中打开了*.class文件。
示例:

class Debug
{
    // setting
    public static final boolean DEBUG = false;
    void print_checked( String s )
    {
        if( DEBUG )
            System.out.print( s );
    }
    void print_unchecked( String s )
    {
        System.out.print( s );
    }
}

public class Main 
{
    public static void main(String[] argc)
    {
        Debug debugger = new Debug();
        debugger.print_checked(" This method 1");
        if (debugger.DEBUG)
            debugger.print_unchecked( "Or this method 2");
    }
}

jd-gui:

// Debug.class
import java.io.PrintStream;
class Debug
{
  public static final boolean DEBUG = false;
  void print_checked(String paramString) {
  }
  void print_unchecked(String paramString) {
    System.out.print(paramString);
  }
}
// Main.class
public class Main
{
  public static void main(String[] paramArrayOfString)
  {
    Debug localDebug = new Debug();
    localDebug.print_checked(" This method 1");
  }
}

如您所见,方法“print_checked”保留在Main.class代码中,但“print_unchecked”被删除。我不确定,但我认为空方法“print_checked”也可能被 Oracle JVM 忽略。

关于Java 最终 boolean 优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24527232/

相关文章:

java - 如何集成 Spring 和 JSF

c++ - 使用const bool删除调试信息时的编译器优化

c# - 如何正确比较列表

java - 为什么我无法对 Edit text int 进行操作?

java - SBT 0.13.6 Windows 8 - Unresolved 依赖关系

java - 在java中,使引用变量可变,是否也会使其所有字段也可变?

arrays - 在 Julia 中将数组拆分为训练集和测试集的有效方法是什么?

python - Python 中的操作顺序和快速计算

javascript - 用于在网格中的所需位置周围查找空单元格的算法

java - 监听多个目录以在 Java 中创建文件