Wednesday, June 13, 2018

String vs StringBuilder C#

String
Namespace: System
 String is an immutable type. That is, each operation that appears to modify a String object actually creates a new string.
Consider using the String class under these conditions:
  1. When the number of changes that your code will make to a string is small.
  2. When you are performing a fixed number of concatenation operations, particularly with string literals. In this case, the compiler might combine the concatenation operations into a single operation.
  3. When you have to perform extensive search operations while you are building your string. The StringBuilder class lacks search methods such as IndexOf or StartsWith. You'll have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder.
String Example
 string stringObj = "Hello Sam";
 // create a new string instance instead of changing the old one
 stringObj += " How Are";
 stringObj += " You ??";
Console.WriteLine(stringObj );
Stringbuilder
Represents a mutable string of characters. This class cannot be inherited. 
    Namespace: System.Text

StringBuilder is mutable, means when you create string builder object you can perform any operations 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.

Consider using the StringBuilder class under these conditions:

  • When you expect your code to make an unknown number of changes to a string at design time (for example, when you are using a loop to concatenate a random number of strings that contain user input).

  • When you expect your code to make a significant number of changes to a string.

StringBuilder  Example
 

 StringBuilder stringBuilderObj = new StringBuilder("");
 stringBuilderObj .Append("Hello Sam");
 stringBuilderObj .Append("How Are You ??");

Console.WriteLine(stringBuilderObj.ToString());

No comments:

Post a Comment