Skip to main content

Posts

Showing posts from October, 2023

C# Performance Improvement - The Power of StringBuilder

 Often when we are wring code we don't think about performance and go with the default options available to achieve a task. String concatenation is one such scenario. If you are doing simple and few string catenations, then you can use the following result = string1 + string2; string1+= string2; result = String.Concat(string1,string2); String.Format and string interpolation are few other options.  However when you are performing large and repetitive  operation, string catenation can be expensive. Here is an example to prove the point.  As you can see it took 41 seconds to perform 100k string catenation. Now lets replace this with StringBuilder and see.  8 ms!!!!!! That is a massive performance difference. Hope you get the point. More info on StringBuilder can be found here https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=net-7.0