How to use StringBuilder wisely?

Modifying immutable structures like strings must be done by copying the structure, and by that, consuming more memory and slowing the application’s run time (also increasing GC time, etc…). StringBuilder comes to solve this problem by using the same mutable object for manipulations. However: when concatenating a string in compile time as the following: string … Read more

Why StringJoiner when we already have StringBuilder?

StringJoiner is very useful, when you need to join Strings in a Stream. As an example, if you have to following List of Strings: final List<String> strings = Arrays.asList(“Foo”, “Bar”, “Baz”); It is much more simpler to use final String collectJoin = strings.stream().collect(Collectors.joining(“, “)); as it would be with a StringBuilder: final String collectBuilder = … Read more

StringWriter or StringBuilder

I don’t think any of the existing answers really answer the question. The actual relationship between the two classes is an example of the adapter pattern. StringWriter implements all its Write… methods by forwarding on to an instance of StringBuilder that it stores in a field. This is not merely an internal detail, because StringWriter … Read more

Best practices/performance: mixing StringBuilder.append with String.concat

+ operator String s = s1 + s2 Behind the scenes this is translated to: String s = new StringBuilder(s1).append(s2).toString(); Imagine how much extra work it adds if you have s1 + s2 here: stringBuilder.append(s1 + s2) instead of: stringBuilder.append(s1).append(s2) Multiple strings with + Worth to note that: String s = s1 + s2 + … Read more

When to use StringBuilder?

I warmly suggest you to read The Sad Tragedy of Micro-Optimization Theater, by Jeff Atwood. It treats Simple Concatenation vs. StringBuilder vs. other methods. Now, if you want to see some numbers and graphs, follow the link 😉

Is it better to reuse a StringBuilder in a loop?

The second one is about 25% faster in my mini-benchmark. public class ScratchPad { static String a; public static void main( String[] args ) throws Exception { long time = System.currentTimeMillis(); for( int i = 0; i < 10000000; i++ ) { StringBuilder sb = new StringBuilder(); sb.append( “someString” ); sb.append( “someString2″+i ); sb.append( “someStrin4g”+i … Read more