Thursday, November 23, 2017

String vs StringBuilder and its uses ( c# / .NET)


string


String uses heap memory and is immutable. Whenever a string is modified, i.e concatenated,replaced or removed, a new heap memory is allocated each time. Hence, multiple modification of string can affect performance. String can be used and is efficient when string modifications are not done multiple time.

Use in cases like this:

string myStr = "This is my test string. It can be simple strings such as headers, texts or some static strings to be displayed";

Do not use in cases like this:

string myStr = "Many times to be concatenated";
for(int i = 1;i<100;i++)
{
myStr = myStr + "Some additional strings";
}

StringBuilder


StringBuilder uses stack memory and is mutable. Whenever string is appended to StringBuilder, no new memory is allocated but strings are appended into string builder itself. This has great performance implication and hence faster in cases like appending/concatenating many strings.

Use in cases like this:

StringBuilder myStringBuilder = new StringBuilder();
            for (int i = 1; i < 100; i++)
            {
                myStringBuilder.Append("Some additional strings");
            }

Do not use in cases like this:

   StringBuilder myStringBuilder = new StringBuilder();
            myStringBuilder.Append("This is my test string.");
            Console.WriteLine(myStringBuilder.ToString()); // output to console window

No comments:

Post a Comment