Friday, October 25, 2013

When we use StringBuilder in Java

If you use String concatenation in a loop (something like:
String s = "";
for(int i = 0; i < 100; i++) {
s
+= ", " + i;
}
then you should use a StringBuilder (not StringBuffer) instead of a String, because it is much faster and consumes less memory.
If you have a single statement:
String s = "1, " + "2, " + "3, " + "4, " ....;
then you can use Strings, because the compiler will use StringBuilder automatically.

No comments:

Post a Comment