我的问题最好用一个例子来提出。
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/