rulururu

post String vs. StringBuilder / StringBuffer

February 26th, 2008

Filed under: .NET, Java — Kai @ 6:22 pm

Some time ago I learned when to use StringBuilder instead of String. Now I want to know the differences and advantages exactly.

As a C++ developer when working with .NET I soon notices the difference about the data types in .NET, especially the standard string object.
A standard .NET string object is immutable.

According to that this is pretty inefficient:

String s;
for (.;.;.) s += "something";

For each +=, the String’s content needs to be copied into a new instance that has a bit more space at the end for “something”.

A better solution is StringBuilder which is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations.

Also in Java String objects are constant strings. Once they are initialized and populated, the value and memory allocation is set. If the value changes in any way, a new object is created for the new value.

But there’s a difference in Java:
StringBuilder was added in Java 5. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.

StringBuffer should be used for multi-threaded applications.
But you have to be careful the StringBuffer class is only available in Java not in .NET languages, here it’s just StringBuilder for single- and multi-threaded applications.

The usage of a .NET StringBuilder is as simple as expected:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
for(int i=0; i<1000; i++)
{
    sb.Append("something");
    sb.Append(12);
    sb.Append(DateTime.Today);
    sb.AppendFormat("{0}: {1} ", i, "times passed the loop");
}
 
String out = sb.ToString();

Append() is overriden for lots of types.

Using Java it’s about the same:

String sum = new StringBuffer().append(40.00).append(" Dollar").toString();

Every time you add two strings using + operator, a new string allocation is reserverd in memory and used for this new string. So let’s say, you are adding strings 100 times using + operator, there will be 100 new memory allocations. In case of StringBuilder, there will only be one memory allocation.

StringBuilder provies a lenght() and a capaitiy() method:

When creating a new StringBuilder

StringBuilder sb = new StringBuilder();

the length is is 0 but the capacity is 16.

When creating a StringBuilder with a String in constructor

StringBuilder sb = new StringBuilder("something");

now length is the length of “something” (8) and the capacity is 16 + 8

If you expect that your buffer will need a capatity of 1000 you can initalize the StringBuilder with a buffersize:

StringBuffer sb = new StringBuffer(1000);
      System.out.println(sb.length());         // prints 0
      System.out.println(sb.capacity());       // prints: 1000

The length() always returns the number of chars in the builder, the number returned by capacity() is the same or bigger than length and tells you how many chars are left in the buffer. If no buffer is left the Builder has to reallocated new memory space, which takes time.
The StringBuffer should be initalized with the expected buffersize to avoid time-consuming reallocation.

You’d always be aware of the fact that the first time creating a StringBuilder costs time - if you just add three String together it will definetely be slower to use a Builder than concatenating them the common way.

Finally I got a visualized comparison of both:

compare SB and String

The numbers at the x-axis represent the quantity of iterates.

The blue line is the performance of the pure String approach. The red line is StringBuilder at its basic settings.
The green line represents a StringBuilder initialized to the size of the final string.

StringBuilder performance can sometimes be a bit tricky because there’s kinda “break-even-point” you always keep in mind.

A simple rule of tumb is:
If you have to concatenate a string more than 10 times, it’s better to use StringBuilder.

5 Comments »

  1. […] 2.8 Working With Strings Don’t Use String.Format() to Concatenate Strings. While string-formatting routines built into .NET are very useful for globalization and other tasks, they’re not meant to be used for appending strings to each other. You’d better prefer Stringbuilders as I explained in this post. […]

    Pingback by Kai’s Blog » Tipps for writing good performanced code in .NET — May 6, 2008 @ 5:52 pm

  2. […] between these two classes is that stringbuffer is faster than string when performing simple …http://bka-bonn.de/wordpress/index.php/2008/02/26/string-vs-stringbuilder-stringbuffer/Object-Oriented Programming in Java Session -215 TCS Confidential string vs. stringbuffer Compile […]

    Pingback by string vs stringbuffer — May 30, 2008 @ 9:25 pm

  3. You can see the some more information from the following link
    http://www.computersight.com/Programming/Java/Compare-String-Stringbuffer-and-Stringbuilder.141705

    Comment by chendra — June 18, 2008 @ 1:37 pm

  4. First of all, thanks google to redirect me to this bka-bonn.de.!! its an amazing page!!

    Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?

    Comment by vaio mouse — March 9, 2011 @ 1:00 pm

  5. wonderful post you have indeed covered the topic with great details with stats and graph. I have also blogged my experience as String vs StringBuffer vs StringBuilder let me know how do you find it.

    Comment by JP @ garbage collection java — August 13, 2011 @ 4:02 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)