Monday, February 19, 2007

String vs StringBuilder

Take a look at the code given below

string str = string.empty;

for(int i= 0 ; I < 100; i++)

{

str += i.ToString();

}

You should never use string concatenation inside a loop, the reason for this being that strings in java and c# are Immutable.What this mean is that each time you concatenate a string, a whole new string object is created with the older value appended to the concatenated value, ok what happens to the older string object ?? well it is left for the garbage collector.

So we got two points here

1) object creation means processing power and memory usage 2) in this example the garbage collector needs to clean up nearly 100 string objects !!!

So what’s the solution ??

Use StringBuilder class (C# - found in the System.Text anmespace), StringBuilder (java not sure of the namespace).

What StringBuilder class does is it actually appends, without actually creating a string object on concatenating , therefore u will be using only one StringBuilder instance in this example, which basically means less processing power and memory usage when instantiationg the StringBuilder instance and garbage collector need to clean only one object !!

Revise code

StringBuilder builder = new StringBuilder(100);

for(int i= 0 ; I < 100; i++)

{

builder.Append( i);

// Use builder.toString() to get the whole string back

}

But , don’t over use StringBuilders as well, for an example, don’t use StringBuilders when u try to concatenate 2 strings, this degrades performance

StringBuilder class has methods that can be used to optimize the string concatenations, for an example a stringBuilder object can be created using a specified string length to store like StringBuilder builder = new StringBuilder(100)

Any question on this or If u want to know how StringBuilders work internally ??, please send me a reply.

3 comments:

  1. A nice one...

    Seems you are having a nice time in your new project.

    BTW it's really better to set the initial size for the StringBuilder at the time you create it. If you look at the IL you'll find that if not specified, as I can recall, the initial size is default to 16. So, when ever you append more items & when it exceeds the default size - it has to call a seperate function to increase it's size - and this is a performance hit.

    ReplyDelete
  2. Thanx, Prabth, your are correct, keep sending u'r expertise, it helps me a lot has a starter!!!.
    I also found out that it's better you use the Append(int) method(I had wrriten the code has Append(i.ToString()), Where i is an Integer), The reason is that overloads make way to correctly convert the valus passed using the current Cultute info, More on this...

    ReplyDelete