简体   繁体   中英

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(",");
        ....
    }
}
....

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM