syker
syker

Reputation: 11272

Scoping a StringBuilder inside a for loop

When would you ever want to scope a String Builder inside a for loop?

Sample Code:

....
for (int i=0; i<cnt; i++) {
    ....
    {
        StringBuilder sb = new StringBuilder();
        sb.append(",");
        ....
    }
}
....

Upvotes: 0

Views: 937

Answers (3)

M. Jessup
M. Jessup

Reputation: 8222

If the code following the inner loop is doing something that requires a large amount of memory, and the StringBuilder inside the inner loop is also large then you might want to have it locally scoped so it would be elligible for the GC to free memory afterwards. Otherwise I agree with JBristow that it should be scoped outside the loop and cleared (and possibly trimToSize()'d) at the start of the inner loop.

Upvotes: 0

rrhartjr
rrhartjr

Reputation: 2114

If you were doing it in combination with another external StringBuilder.

StringBuilder sbAll = new StringBuilder();
for (int i=0; i<cnt; i++) {
    ....
    {
        StringBuilder sb = new StringBuilder();
        sb.append(",");
        sbAll.append(sb.toString());
    }
}

The question is what are you doing inside the loop that's cute enough to need a separate StringBuilder? I guess it is possible.

Upvotes: 0

Jon Bristow
Jon Bristow

Reputation: 1725

Well, aside from the slight code smell of creating new objects inside a loop, I could see you creating a StringBuilder inside a for loop to generate a long string for each item in the for-loop.

However, you could also scope it outside of the for loop and clear it on each pass. Depends on how you think it would be easier to read.

Upvotes: 2

Related Questions