String
String is immutable and when you do the operation (Insert, Delete and Update) with string object, every time it creates a new memory for the string object.StringBuilder
StringBuilder is mutable and when you do the operation (Insert, Delete and Update) with StringBuilder object, it doesn’t create a new memory for the StringBuilder object. Every time it updates the same memory so stringBuilder is faster than String.StringBuilder object is also provide many functions which you can use to do the operations.
Example - String and StringBuilder time difference.
class StringAndStringBuilder{
static void Main()
{
string str = string.Empty;
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 1000; i++)
{
str += i.ToString();
}
watch.Stop();
Console.WriteLine("String time in timer ticks :- "+
watch.ElapsedTicks.ToString());
watch.Reset();
StringBuilder sb = new StringBuilder();
watch.Start();
for (int i = 0; i < 1000; i++)
{
sb.Append(i.ToString());
}
watch.Stop();
Console.WriteLine("StringBuilder time in timer ticks :- " +
watch.ElapsedTicks.ToString());
Console.ReadLine();
}
}
Output
String time in timer ticks :- 17236716StringBuilder time in timer ticks :- 509064
No comments:
Post a Comment