Saturday, May 5, 2018

C# : What is the difference between string and StringBuilder in c#

StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for performance:

String: 

String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like:

ASP.NET
Note:
  • It’s an immutable object that hold string value.
  • Performance wise string is slow because its’ create a new instance to override or change the previous value.
  • String belongs to System namespace.
StringBuilder:
System.Text.Stringbuilder is mutable object which also hold the string value, mutable means once we create a System.Text.Stringbuilder object we can use this object for any operation like insert value in existing string with insert functions also replace or append without creating new instance of System.Text.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare than System.String. Let’s have an example to understand System.Text.Stringbuilder like:

ASP.NET
Note:
  • StringBuilder is a mutable object.
  • Performance wise StringBuilder is very fast because it will use same instance of StringBuilder object to perform any operation like insert value in existing string.
  • StringBuilder belongs to System.Text.Stringbuilder namespace.

No comments:

Post a Comment