Possible Duplicate:
Should I use Java's String.format() if performance is important?
I was wondering if is good to use String.format in Java apps instead of StringBuilder… so, I just write a simple test, like this:
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);
}
And the results where:
238
15
So, if my test is valid, StringBuilder is faster than String.format. OK.
Now, I start thinking how String.format works. Is it a simple String concatenation, like "test " + i?
What the differences between StringBuilder concatenation and String.format? Is there a way simple as String.format and fast like StringBuilder?
I wrote a quick caliper benchmark to compare
String.format()vs.StringBuilder,StringBuffer, normalString+operator,String.replace()andString.concat()methods:The results follow (Java 1.6.0_26-b03, Ubuntu, 32 bits):
Clearly
String.format()is much slower (by an order of magnitude). AlsoStringBufferis considerably slower thanStringBuilder(as we were taught). FinallyStringBuilderandString+operator are almost identical since they compile to very similar bytecode.String.concat()is a bit slower.Also don’t use
String.replace()if simple concatenation is sufficient.