Showing posts with label StringBuilder. Show all posts
Showing posts with label StringBuilder. Show all posts

Wednesday, May 2, 2012

Strings are from earth and StringBuilder from mars.

Introduction


I was happily married to string for a long time until I came to know the reality that “Strings are immutable” and not suitable for all scenarios. Recently I was working on a heavy HTML parser application and the program used to go out of memory frequently. The completely HTML parsing logic was using string variables.

After reading around I came to know the main reason was the immutable behavior of string. Immutable means once the data is assigned cannot be changed.

For instance if you are looping using a string variable like the code given below. Every assignment to the string creates new copies of variables and the previous copy is sent for garbage collection. So the below for loop generates different memory copies of data and the recently created is the current value.

   

Now you must be wondering why this absurd behavior. Any lame person (like me) can conclude this is not efficient and neither looks logical.

The sacrifice for thread safety


Before I start with the solution I wanted to understand why Microsoft team thought about this weird behavior. Thanks to http://stackoverflow.com/questions/2365272/why-net-string-is-immutable things started looking logical.

If you are using string variables in multithreaded scenarios every thread modification will create new copy of memory ensuring that you do not land in to multi-threaded issues. In other words thread safety is built-in by itself when new copies of data are created.

Not all work on ships


The next thing which started itching me is what if my application is not multi-threaded. What if my main motive is to save memory resources and ensure that I do not go out of memory issues?. Here’s comes the hero from mars “StringBuilder”.

“Stringbuilder” are not immutable, in other words if you change the variable data the same memory location is modified. VOW, that looks lot of memory saving during heavy concatenation operation as compared to string.

 

I wanted to see for myself that earth is flat


As a curios developer it was difficult for me to digest that internally string creates different copies of data. Out of curiosity I downloaded the CLR Profiler and ran two test of code as shown below.

One for string as the below.

string x ="";

for (inti = 0; i< 10000; i++)
{
x = "Shiv"+ x;

}


 

One for string builder.

StringBuilder x = newStringBuilder();

for (inti = 0; i< 10000; i++)
{
x.Append("Shiv");

}



Watch the allocated bytes, 400235631 bytes is way greaterthan 136597bytes.

Watch the video below for the real demo


If you do not believe what I have written see the actual video demo as follows

Tuesday, July 26, 2011

C# and .Net Interview Questions”- Why String Builders are faster than strings?


Strings: - strings are also called as immutable because every time you
store a new value in string a new copy is created in the memory location.





String builders: - string builders are also called as mutable because
every time you store a new value in string builder

it actually appends the value in the memory location. This means insertion
is done on existing string.

Let’s demonstrate a small example which will give a clear idea on who is faster
string builder or string.

This is very simple three steps procedure as follows.

Step1: -

Create a new console application like below diagrams.


Go to file > New > Project > Console Application and Click Ok.




Step2: -


Import System.Text namespace in your application.

usingSystem.Text;

Step3: -

Write the below code snippet in your main class.

staticvoid Main(string[] args)
{
while (true)
{
Console.WriteLine("*********Begin Test*********");
Console.WriteLine("============================");
Console.WriteLine("Creating string");
Console.WriteLine();//for having a gap in the lines.
List<string>strlist = newList<string>();
for (int i = 0; i < 30000; i++)
{
strlist.Add(i.ToString());
}
Console.WriteLine("Time taken by string to concate....");
Console.WriteLine();
DateTime start = DateTime.Now;
stringConcateString = string.Empty;
foreach (strings instrlist)
{
ConcateString += s + "";
}
TimeSpan time = (DateTime.Now - start);
Console.WriteLine("Total Time : {0} MilliSeconds", time);
Console.WriteLine("============================");
Console.WriteLine("Creating StringBuilder");
Console.WriteLine();
start = DateTime.Now;
StringBuildersb = newStringBuilder();
foreach (strings instrlist)
{
sb.Append(s + "");
}
time = (DateTime.Now - start);
Console.WriteLine("Time taken by StringBuilder to concate....");
Console.WriteLine();
Console.WriteLine("Total Time : {0} MilliSeconds", time);
Console.WriteLine();
Console.WriteLine("**********End Test**********");
Console.ReadLine();
}

Now run your application and you will see the result like below diagram.


In the above result you can see that the time taken by the string to concateis
greater than the time taken by the string builder to concate, this indicates that the string builders performs faster than the strings.


For more information about generic, please watch the below video.



Please click here to see more C# and Dotnet interview questions

Regards,

Visit Authors blog for more Most asked c# interview questions

Tuesday, February 22, 2011

C# interview question :- Why is stringbuilder concatenation more efficient than simple string concatenation?

C# interview question :- Why is stringbuilder concatenation more efficient than simple string concatenation?


Answer:

This question is one of the favorites question which comes during c# interviews and the interviewer is not only expecting which one of them is more efficient. But he is also expecting the reason for the same.

In order to understand the same better lets consider the below scenario where we have two lines of code which does string concantenation.
For a simple string concatenation code shown below it will create 3 copies of string in memory.

//The below line of code Creates one copy of the string
string str = "shiv";

/* The below line of  code creates three copies of string object one for
the concatenation  at right hand side and the other for new value at the
left hand side. The first old allocated memory is sent for garbage
collection.*/
str = str + "shiv";

When you use the string builder for concatenation it will create only one copy of the object.

/* The below code uses string builder and only one
object is created as compared to normal string where we have 3 copies created*/
StringBuilder objBuilder = new StringBuilder();
objBuilder.Append("shiv");

Ok now summarizing what should we say to the interviewer.
String is immutable. Immutable means once assigned it can not be changed. Thats why it creates more copies of the object as it can not use the same instance.String builder is mutable ,in other words the same object will changed rather than creating new objects.
So string builder is more efficient as compared to simple string concatenation.


See my 300 important c# interview questions and answers