Newline character in StringBuilder

I would make use of the Environment.NewLine property. Something like: StringBuilder sb = new StringBuilder(); sb.AppendFormat(“Foo{0}Bar”, Environment.NewLine); string s = sb.ToString(); Or StringBuilder sb = new StringBuilder(); sb.Append(“Foo”); sb.Append(“Foo2”); sb.Append(Environment.NewLine); sb.Append(“Bar”); string s = sb.ToString(); If you wish to have a new line after each append, you can have a look at Ben Voigt’s answer.

Performance between String.format and StringBuilder

What is “better” solely depends on your requirements: For instance String Builder will be faster, but the code will be much more unreadable, and and it would be easier to make a mistake. On the other hand String.format() produces more readable code at the cost of performance. JMH benchmark to illustrate the performance difference (notice … Read more

Dumping a Java StringBuilder to File

As pointed out by others, use a Writer, and use a BufferedWriter, but then don’t call writer.write(stringBuilder.toString()); instead just writer.append(stringBuilder);. EDIT: But, I see that you accepted a different answer because it was a one-liner. But that solution has two problems: it doesn’t accept a java.nio.Charset. BAD. You should always specify a Charset explicitly. it’s … Read more

How do I prove programmatically that StringBuilder is not threadsafe?

Problem I am afraid the test you have written is incorrect. The main requirement is to share the same StringBuilder instance between different threads. Whereas you are creating a StringBuilder object for each thread. The problem is that a new Threadsafe() initialises a new StringBuilder(): class Threadsafe { … StringBuilder sb = new StringBuilder(str); … … Read more

Java: String concat vs StringBuilder – optimised, so what should I do?

I think the use of StringBuilder vs + really depends on the context you are using it in. Generally using JDK 1.6 and above the compiler will automatically join strings together using StringBuilder. String one = “abc”; String two = “xyz”; String three = one + two; This will compile String three as: String three … Read more

StringBuilder for PHP

Note: This answer is from 2010, there might be stringbuilders that can improve the performance by now (judging from the comments below). I have not worked with php for a long time so my knowledge is not up to date. This answer might be out dated. The following question might provide interesting information as well, … Read more