String Vs StringBuilder

  • If there are lot of changes or manipulations to be made on a string then it is better to use a StringBuilder Class. StringBuilder supports various functions such as Replace, Remove, Insert, Equals, Append, ..etc.
  • And one important difference is String is immutable. Immutable means the data value cannot be changed. That means when you want to change the value of a string, a new instance of it is created and the previous one will be discarded. whereas if you take a StringBuilder the value initially assigned to the StringBuilder object can be changed, as it is just a object we need not create again a new object, we can just modify it.
A simple program will show the difference.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace immutable
{
class Program
{
static void Main(string[] args)
{
string str1 = "Hi";
string str2 = str1;
str1 = "Hello"; // a new string variable is created and there "Hello" is stored
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadLine();
StringBuilder strBuilder1 = new StringBuilder("Hi");
StringBuilder strBuilder2 = strBuilder1;
strBuilder1.Replace("Hi","Hello");
Console.WriteLine(strBuilder1);
Console.WriteLine(strBuilder2);
Console.ReadLine();
}
}
}

Output:
Hello
Hi
Hello
Hello

Comments

Popular posts from this blog

Network Security: LAN manager authentication level

Cisco AnyConnect Secure Mobility Client - VPN service not available. The VPN agent service is not responding