Difference between String and StringBuilder

Here is the differences between String and StringBuilder

A String instance is immutable, that is we cannot change it after it was created. If we perform any operation on a String it will return a new instance(creates a new instance in memory) instead of modify existing instance value.


string str = "Hello"; str = str + Environment.NewLine; str = str + "Welcome To DotnetLearners.";

StringBuilder is mutable, that is if we perform any operation on StringBuilder it will update the existing instance value and it will not create new instance.


StringBuilder sb = new StringBuilder(); sb.Append("Hello"); for (int i = 0; i < 100; i++) sb.AppendLine("Welcome " + i.ToString());

When you need to perform lot of operations on a String then use StringBuilder, when just want to concatenate 3 or 4 Strings use String(Because of StringBuilder initialization overhead). When we are performing large operation on strings StringBuilder will give you best performance.