String vs StringBuilder C#.Net with code example

String vs StringBuilder C#.Net with code example

String

C# class which offers capability to store any type of string data into a variable. Strings are immutable (non-modifiable) cause performance overhead because each time we modify a string it creates a copy of modified instance into the memory, hence, as a practice string should be avoided for large string operations. Following is the example where we are toggling the string 10000 times by putting in a loop and capturing total time taken for the operation in milliseconds.

Code example

static void Main(string[] args)
{
	//String operation
	string testString = "Testing";

	Stopwatch oWStopwatch_one=new Stopwatch();

	oWStopwatch_one.Start();

	for (int i = 1; i < 10000; i++)
	{
		testString += i;
	}

	oWStopwatch_one.Stop();

	//print result
	Console.WriteLine("Total time taken by String operation: " + oWStopwatch_one.ElapsedMilliseconds);
	Console.ReadKey();
}

Output

StringBuilder

C# class extended from System.Text offers great string manipulation capability. It offers various methods to add, edit or delete a string. The performance of StringBuilder is much faster than String, hence it is recommended to use StringBuilder for large string operations. Using same code except regular string is replaced with StringBuilder object.

Code example

static void Main(string[] args)
{
	
	//StringBuilder Operation
	StringBuilder oStringBuilder=new StringBuilder();

	Stopwatch oWStopwatch_two = new Stopwatch();

	oWStopwatch_two.Start();

	for (int i = 1; i < 10000; i++)
	{
		oStringBuilder.Append(i);
	}

	oWStopwatch_two.Stop();

	//print result
	Console.WriteLine("Total time taken by StringBuilder operation: " + oWStopwatch_two.ElapsedMilliseconds);
	Console.ReadKey();
}

Output

Conclusion

If you notice, string operation took 202ms where StringBuilder took only 2ms. StringBuilder can also be limit for range of characters by passing number of characters to the default constructor while instantiating the object as given below:

StringBuilder oStringBuilder=new StringBuilder(10000);

Above StringBuilder class object got the limit of 10000 chars max. Also by default it reserves 16 bytes in the memory and as long as string grows the bytes grows twice from its previous capacity.

Next >> var vs dynamic data types in C#.Net with code example

Leave a Reply

Your email address will not be published. Required fields are marked *