Thursday, May 8, 2008

Difference between String and StringBuilder

C# and Java What is the difference between String and StringBuilder classes?

String is an object. Both String and StringBuilder class stores strings

String :

String is immutable i.e. Read only, non updatable.

Example: String somename = "Lavakumar";

We cannot change a String object after creating one.It means we can’t change the value internally.

If you want change the value of somename object a new object is created then the reference of somename object is changed to new object. The old object is collected by GC ( garbage collecter).

Example: String somename = "sangeetham";

New object with value “sangeetham” is created. Then the reference of somename variable changed from “Lavakumar” object to “sangeetham” object. And the old object “sangeetham” is collected by GC (garbage collector).

Example:

using System;

sing System.Text;

public class string

{

static void Main()

{

DateTime start = DateTime.Now;

string x = "";

for (int i=0; i < 100000; i++)

{

x += "~";

}

DateTime end = DateTime.Now;

Console.WriteLine ("Time taken: {0}", end-start);

}

}

It takes nearly 10 seconds. Double the number of iterations, and it takes over a minute.

The problem is that strings not changeable (immutable). Just because we're using "+=" here doesn't mean the runtime actually appends to the end of the existing string. In fact, x += "!"; is absolutely equivalent to x = x+"!";. The concatenation here is creating an entirely new string, allocating enough memory for everything, copying all the data from the existing value of x and then copying the data from the string being appended ("~"). As the string grows, the amount of data it has to copy each time grows too, which is why the time taken didn't just double when I doubled the number of iterations.

String Builder :

String Builder is mutable i.e. subject to change.(we can change the value, updatable)

Default some space is allocated for String Builder.

If you are using for loop definitely go to stringBuilder.

It gives better performance when we are adding more than 10 strings.

In this there is no object creation for each addition. So String Builder is faster than String.

String builder initially some default memory.

By using StringBuilder.Append() method we can append Strings.

Example:

using System;

using System.Text;

public class stringbuild

{

static void Main()

{

DateTime start = DateTime.Now;

StringBuilder builder = new StringBuilder();

for (int i=0; i < 100000; i++)

{

builder.Append("~");

}

string x = builder.ToString();

DateTime end = DateTime.Now;

Console.WriteLine ("Time taken: {0}", end-start);

}

}

It takes nearly 30-40ms only. The time taken is roughly linear in the number of iterations (i.e. double the iterations and it takes twice as long). It does this by avoiding unnecessary copying - only the data we're actually appending gets copied. StringBuilder maintains an internal buffer and appends to that, only copying its buffer when there isn't room for any more data. (In fact, the internal buffer is just a string - strings are immutable from a public interface perspective, but not from within the mscorlib assembly.) We could make the above code even more efficient by passing the final size of the string (which we happen to know in this case) to the constructor of StringBuilder to make it use a buffer of the right size to start with - then there'd be no unnecessary copying at all. Unless you're in a situation where you have that information readily to hand though, it's usually not worth worrying about - StringBuilder doubles its buffer size when it runs out of room, so it doesn't end up copying the data very many times anyway.

visualized comparison of both:

clip_image002[6]

                                                                                     no of iterates

clip_image001( blue)is the performance of the pure String approach.

clip_image002(red) is StringBuilder at its basic settings.

clip_image003(green) 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.

Conclusion:
If you have to concatenate a string more than 10 times, it’s better to use StringBuilder.

Read more.....(Thanks to yoda.arachsys)

Read more.....(Thanks to bka-bonn.de)

0 comments:

Google