我们必须一直为日志输出构建字符串等等.在JDK版本中,我们学会了何时使用StringBuffer(许多追加,线程安全)和StringBuilder(许多追加,非线程安全).
有什么建议使用String.format()?它是否有效,或者我们是否被迫坚持连接性能很重要的单线?
例如丑陋的旧式,
String s = "What do you get if you multiply " + varSix + " by " + varNine + "?";
Run Code Online (Sandbox Code Playgroud)
与整洁的新风格(可能很慢),
String s = String.format("What do you get if you multiply %d by %d?", varSix, varNine);
Run Code Online (Sandbox Code Playgroud)
注意:我的具体用例是我的代码中的数百个"单行"日志字符串.它们不涉及循环,所以StringBuilder太重量级了.我String.format()特别感兴趣.
java string performance string-formatting micro-optimization
众所周知,String.format()的性能很糟糕.我看到我的(可能很常见的)典型案例有很大的改进.我多次打印相同的数据结构.让我们想象一下像"x:%dy:%dz:%d"这样的结构.我希望String.format()的主要问题是它必须始终解析格式化字符串.我的问题是:是否有一些现成的类允许只读取一次格式化字符串然后允许在变量参数填充时快速给出字符串?用法应如下所示:
PreString ps = new PreString("x:%d y:%d z:%d");
String s;
for(int i=0;i<1000;i++){
s = ps.format(i,i,i);
}
Run Code Online (Sandbox Code Playgroud)
我知道这是可能的 - 以下是我的快速和肮脏的例子,它正在我正在谈论的事情,并且在我的机器上快约10倍:
public interface myPrintable{
boolean isConst();
String prn(Object o);
String prn();
}
public class MyPrnStr implements myPrintable{
String s;
public MyPrnStr(String s){this.s =s;}
@Override public boolean isConst() { return true; }
@Override public String prn(Object o) { return s; }
@Override public String prn() { return s; }
}
public class MyPrnInt implements myPrintable{
public MyPrnInt(){}
@Override public boolean isConst() …Run Code Online (Sandbox Code Playgroud)