Showing posts with label stringbuilder. Show all posts
Showing posts with label stringbuilder. Show all posts

Java: StringBuilder versus StringBuffer

When it comes to building / joining the strings there are some options. The most popular way is to use '+' operator. However it is not always a good idea because in some circumstances it can cause out of memory related errors. The reason behind that is that whenever you using '+' operator the new string object is created. If this is done in a long loop you may get into troubles ;)

The other options are to use existing Java classes: StringBuilder or StringBuffer.

StringBuilder was introduced in Java 5 so there is a good chance that some old geeks are get used to StringBuffer instead.

In most cases StringBuilder should be used. It is more efficient than his older brother but it does not support multi-threaded environment. In other hand StringBuffer is synchronized and should be used multithreads.

But please do not give up on using '+' operator - it is still good way when there are no loops and when it comes to quickly join some lines intro a string.