Which is better System.String or System.Text.StringBuilder classes in C#?


The main difference is StringBuilder is Mutable whereas String is Immutable.

String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of string type in memory.

On the other hand, StringBuilder is mutable. Means, if we create a string builder object then we can perform any operation like insert, replace or append without creating new instance for every time. It will update string at one place in memory doesn’t create new space in memory.

Example

 Live Demo

using System;
using System.Text;
class DemoApplication{
   public static void Main(String[] args){
      String systemString = "Hello";
      StringConcat(systemString);
      Console.WriteLine("String Class Result: " + systemString);
      StringBuilder stringBuilderString = new StringBuilder("Hello");
      StringBuilderConcat(stringBuilderString);
      Console.WriteLine("StringBuilder Class Result: " + stringBuilderString);
   }
   public static void StringConcat(String systemString){
      String appendString = " World";
      systemString = String.Concat(systemString, appendString);
   }
   public static void StringBuilderConcat(StringBuilder stringBuilderString){
      stringBuilderString.Append(" World");
   }
}

Output

The output of the above example is as follows −

String Class Result: Hello
StringBuilder Class Result: Hello World
  • Use of StringConcat Method: In this method, we are passing a string “Hello” and performing “systemString = String.Concat(systemString, appendString);” where appendString is “ World” to be concatenated. The string passed from Main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and systemString in StringConcat() stores reference of the new string. But the references systemString in Main() and StringConcat() refer to different strings.

  • Use of StringBuilderConcat Method: In this method, we are passing a string “Hello” and performing “stringBuilderString.Append(" World");” which changes the actual value of the string (in Main) to “Hello World”. This is due to the simple fact that StringBuilder is mutable and hence changes its value.

Updated on: 04-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements