Click here to Skip to main content
15,867,308 members
Articles / General Programming / String

Strings are from earth and StringBuilder from mars.

Rate me:
Please Sign up or sign in to vote.
4.95/5 (38 votes)
1 May 2012CPOL2 min read 52.6K   19   22
Here we will discuss about Strings and Stringbuffer in .NET.

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.
 
  Image 1 

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.
 
  Image 2 

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;

}
Image 3

One for string builder.

StringBuilder x = newStringBuilder();

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

}
Image 4

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 Image 5

For Further reading do watch  the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
Question5ed Pin
Karthik_Mahalingam24-May-16 15:45
professionalKarthik_Mahalingam24-May-16 15:45 
GeneralMy vote of 5 Pin
Rahul Rajat Singh28-Jun-12 1:12
professionalRahul Rajat Singh28-Jun-12 1:12 
GeneralMy vote of 5 Pin
Farhan Ghumra17-Jun-12 19:23
professionalFarhan Ghumra17-Jun-12 19:23 
GeneralMy vote of 5 Pin
Perić Željko7-Jun-12 10:29
professionalPerić Željko7-Jun-12 10:29 
QuestionNice Pin
BillW337-Jun-12 6:30
professionalBillW337-Jun-12 6:30 
GeneralMy vote of 4 Pin
Chamila Nishantha5-May-12 18:30
Chamila Nishantha5-May-12 18:30 
QuestionDon't forget about... Pin
GamersWanted4-May-12 4:10
GamersWanted4-May-12 4:10 
SuggestionRe: Don't forget about... Pin
Richard Deeming10-May-12 9:01
mveRichard Deeming10-May-12 9:01 
The String.Format code might be more readable, but it's not more efficient.

Behind the scenes, it creates a new StringBuilder object, calls its AppendFormat method, and then calls ToString to return the string:

C#
public static string Format(IFormatProvider provider, string format, params object[] args)
{
    if ((format == null) || (args == null))
    {
        throw new ArgumentNullException((format == null) ? "format" : "args");
    }
    StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
    builder.AppendFormat(provider, format, args);
    return builder.ToString();
}


The StringBuilder.AppendFormat method has to work through the format string to replace the placeholders with the specified parameters. The method will allocate an additional StringBuilder instance for each placeholder which includes a format specifier (eg: "{0:D}").

Your first example will typically be compiled as a call to String.Concat(String, String, String), which is optimized to build the string in one go, without using a StringBuilder instance. Even in the worst-case, the two String.Concat(IEnumerable) methods use a StringBuilder.

So, whilst I would prefer your second example for readability, the first is actually more efficient! Smile | :)



"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer


AnswerRe: Don't forget about... Pin
DrWheetos7-Jun-12 11:12
DrWheetos7-Jun-12 11:12 
GeneralMy vote of 5 Pin
thatraja2-May-12 17:56
professionalthatraja2-May-12 17:56 
GeneralRe: My vote of 5 Pin
Shivprasad koirala2-May-12 18:09
Shivprasad koirala2-May-12 18:09 
QuestionStringBuilder does allocate and discard *some* memory Pin
supercat92-May-12 9:56
supercat92-May-12 9:56 
AnswerRe: StringBuilder does allocate and discard *some* memory Pin
Richard Deeming10-May-12 9:09
mveRichard Deeming10-May-12 9:09 
GeneralMy vote of 5 Pin
Nicolas Gordillo2-May-12 8:43
Nicolas Gordillo2-May-12 8:43 
GeneralMy vote of 5 Pin
Brij2-May-12 3:49
mentorBrij2-May-12 3:49 
GeneralMy vote of 5 Pin
BRShroyer2-May-12 2:06
BRShroyer2-May-12 2:06 
GeneralMy vote of 5 Pin
Jαved2-May-12 1:26
professionalJαved2-May-12 1:26 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»2-May-12 0:48
professionalKunal Chowdhury «IN»2-May-12 0:48 
GeneralRe: My vote of 5 Pin
BRShroyer2-May-12 2:01
BRShroyer2-May-12 2:01 
GeneralRe: My vote of 5 Pin
Kunal Chowdhury «IN»2-May-12 2:46
professionalKunal Chowdhury «IN»2-May-12 2:46 
GeneralRe: My vote of 5 Pin
Shivprasad koirala2-May-12 4:06
Shivprasad koirala2-May-12 4:06 
GeneralRe: My vote of 5 Pin
Kunal Chowdhury «IN»2-May-12 4:10
professionalKunal Chowdhury «IN»2-May-12 4:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.