• home
  • Email: trainings@synapseindia.careers

Blogs

back

Use of StringBuilder class over String Class

Jul 13, 2016

A String object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.

You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. When you have finished modifying the value of a StringBuilder object, you can call its StringBuilder.ToString method to convert it to a string.

Consider the below two examples doing the same task by using string class and second is doing through StringBuilder

Example 1: By String Class

using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();

      string str = String.Empty;
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                           false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         str += Convert.ToChar(rnd.Next(1, 0x0530)); 
         if (str.Length % 60 == 0)
            str += Environment.NewLine;          
      }                    
      sw.Write(str);
      sw.Close();
   }
}

Example 2: By using StringBuilder Class

using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      StringBuilder sb = new StringBuilder();
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                                         false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         sb.Append(Convert.ToChar(rnd.Next(1, 0x0530))); 
         if (sb.Length % 60 == 0)
            sb.AppendLine();          
      }                    
      sw.Write(sb.ToString());
      sw.Close();
   }
}