Possible Duplicate:
Should I use Java's String.format() if performance is important?
我想知道在 Java 应用程序中使用 String.format
代替 StringBuilder
是否好...所以,我只写了一个简单的测试,如下所示:
public static void main(String[] args) {
int i = 0;
Long start = System.currentTimeMillis();
while (i < 10000) {
String s = String.format("test %d", i);
i++;
}
System.out.println(System.currentTimeMillis() - start);
i = 0;
start = System.currentTimeMillis();
while (i < 10000) {
String s = new StringBuilder().append("test ").append(i).toString();
i++;
}
System.out.println(System.currentTimeMillis() - start);
}
结果是:
238
15
因此,如果我的测试有效,StringBuilder
比 String.format
更快。好的。
现在,我开始思考 String.format
是如何工作的。它是一个简单的字符串连接,如 "test "+ i
吗?
StringBuilder
连接和String.format
有什么区别?有没有像String.format
一样简单,像StringBuilder
一样快速的方法?
我写了一个快速 caliper比较 String.format()
与 StringBuilder
、StringBuffer
、普通 String
+
运算符、String.replace()
和 String.concat()
方法:
public class StringFormatBenchmark extends SimpleBenchmark {
public void timeStringFormat(int reps) {
while (--reps >= 0) {
String s = String.format("test %d", reps);
}
}
public void timeStringBuilder(int reps) {
while (--reps >= 0) {
String s = new StringBuilder("test ").append(reps).toString();
}
}
public void timeStringBuffer(int reps) {
while (--reps >= 0) {
String s = new StringBuffer("test ").append(reps).toString();
}
}
public void timeStringPlusOperator(int reps) {
while (--reps >= 0) {
String s = "test " + reps;
}
}
public void timeReplace(int reps) {
while (--reps >= 0) {
String s = "test {}".replace("{}", String.valueOf(reps));
}
}
public void timeStringConcat(int reps) {
while (--reps >= 0) {
String s = "test ".concat(String.valueOf(reps));
}
}
public static void main(String[] args) {
new Runner().run(StringFormatBenchmark.class.getName());
}
}
结果如下(Java 1.6.0_26-b03,Ubuntu,32 位):
显然 String.format()
慢得多(一个数量级)。此外,StringBuffer
比 StringBuilder
慢得多(正如我们被教导的那样)。最后,StringBuilder
和 String
+
运算符几乎相同,因为它们编译为非常相似的字节码。 String.concat()
有点慢。
如果简单的连接就足够了,也不要使用 String.replace()
。