鉴于toString()下面的两个实现,首选哪一个:
public String toString(){
return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
Run Code Online (Sandbox Code Playgroud)
要么
public String toString(){
StringBuilder sb = new StringBuilder(100);
return sb.append("{a:").append(a)
.append(", b:").append(b)
.append(", c:").append(c)
.append("}")
.toString();
}
Run Code Online (Sandbox Code Playgroud)
?
更重要的是,鉴于我们只有3个属性,它可能没有什么区别,但你会在什么时候从+concat 切换到 StringBuilder?
正如JEP 280中所写:
更改
String生成的static -concatenation字节码序列,javac以使用invokedynamic对JDK库函数的调用.这将使未来的String串联优化成为可能,而无需进一步更改所设置的字节码javac.
在这里,我想了解invokedynamic调用的用途以及字节码串联的不同之处是invokedynamic什么?
传递多个字符串进行日志记录时,最好使用varargs还是字符串连接?
将在生产环境中禁用日志记录.
考虑以下代码,
public void log(int logLevel, String ... msg) {
if (logLevel >= currentLogLevel) {
for (String m : msg) {
// print the log to file
}
}
}
// calling
log(2, "text1", var1, "text2");
Run Code Online (Sandbox Code Playgroud)
比.
public void log(int logLevel, String msg) {
if (logLevel >= currentLogLevel) {
// print the log to file
}
}
// calling
log(2, "text1" + var1 + "text2");
Run Code Online (Sandbox Code Playgroud)
哪一个在两种情况下都有效(启用/禁用)?