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?
