Reusing StringBuilder or creating a new one? Given that it is better to reuse objects than create new ones when developing with Android, is it worth while deleting the contents of a StringBuilder and reusing it?

StringBuilder b = new StringBuilder();
//build up a string
b.delete(0, b.length());
//reuse it


Compared to:

StringBuilder b1 = new StringBuilder();
//build up a string
StringBuilder b2 = new StringBuilder();
//create a new one
Reusing doesn't need memory allocation, so it could be faster as @Mike Nakis mentioned. On the other hand it leads to ugly code: you use the same variable for two (or more) different purposes which could confuse readers, make maintenance harder. Unless you have a good reason to do that avoid it. I mean, you have a good reason if a profiling shows that creating new StringBuilder instances is a bottleneck in the application.

If you really have to reuse StringBuilders, try accessing them with different names with a helper method:

public static StringBuilder reuseForBetterPerformance(final StringBuilder sb) {
    sb.delete(0, sb.length());
    return sb;
}


Client code:

final StringBuilder b = new StringBuilder();
//build up a string
final StringBuilder c = reuseForBetterPerformance(b);
//reuse it
c.append(...)


It makes the code a little bit more readable, since the method name says why you're reusing the StringBuilder.