java - 如果常量会阻止使用字符串参数,优化器是否会阻止创建字符串参数?

标签 java android logging compiler-optimization

我的问题最好用一个例子来提出。

  public static boolean DEBUG = false;

  public void debugLog(String tag, String message) {
    if (DEBUG)
      Log.d(tag, message);
  }

  public void randomMethod() {
    debugLog("tag string", "message string"); //Example A

    debugLog("tag string", Integer.toString(1));//Example B

    debugLog("tag string", generateString());//Example C 
  }


  public String generateString() {
    return "this string";
  }

我的问题是,在任何示例中,A、B 或 C - 由于字符串最终不会被使用,优化器会删除它吗?

或者换个方式问,做下面的事情会不会更好,从而确保不会创建字符串对象?

  public void randomMethod() {
    if (DEBUG) debugLog("tag string", "message string"); //Example A

    if (DEBUG) debugLog("tag string", Integer.toString(1));//Example B

    if (DEBUG) debugLog("tag string", generateString());//Example C 
  }

最佳答案

似乎第一个代码段没有被删除,但第二个代码段被删除了:

public class TestCompiler {
    public static boolean DEBUG = false;
    private static void debug(Object o) {
        if (DEBUG) {
            System.out.println(o);
        }
    }
    public static void main(String[] args) {
        if (DEBUG) {
            System.out.println(new InnerClass());
        }
        System.out.println("now nested");
        debug(new InnerClass());
    }
    private static final class InnerClass {
        static {
            System.out.println("Innerclass initialized");
        }
    }
}

对于我 (openjdk7),这导致:

now nested
Innerclass initialized

意味着 if (DEBUG) {...} 被移除,但是方法调用没有,因此方法参数被设置。

关于java - 如果常量会阻止使用字符串参数,优化器是否会阻止创建字符串参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711073/

相关文章:

java - 比较对象的两个 ArrayList 时 containsAll 返回 False

Java 数组与类名同名

java - android studio 中同步依赖项时出错,如配置 'compile' 已过时,已替换为 'implementation' 和 'api'

java - 显示键盘时 ListView 不调整大小

java - Junit 测试日志语句

java - 不要将 String 读作正则表达式,而是按原样阅读

java - %20 的 ImagePath 不起作用

android - Jetpack Compose 代码生成期间出现异常

java - 如何超越LogManager警告?

logging - Spring Boot : How can I set the logging level with application. 属性?