神刀安全网

C# Code Optimization Using StringBuilder

Using StringBuilder Wisely

We can optimize our code in some cases by using StringBuilder instead of string. So, what’s the situation where StringBuilder is more efficient than string, I will explain this to you with an example. Consider a case when you are concatenating a string in the same variable continuously in a loop and after the end of the loop you have to use that final value—here you should use StringBuilder’s append method to concatenate, not string variable. Another question is how does code execute fast from using StringBuilder—it’s because of the internal working of these two.

How String Works

Each time we concatenate a string, it creates a new object in memory then copies an old value of the string in a new object, putting new values in that object then pointing our string variable to the newly created object.

How StringBuilder Works

Each time we append a string, we put the new value of the string in the same memory object. We don’t create a new object each time, nor do we copy old values to a new object each time.

Now you can clearly understand why StringBuilder is more efficient in the above scenario.

I will show you some sample code which you can run as a console application to see the difference in speed of the execution of a string versus StringBuilder by yourself.

The timing of the outputs of the code will be something like this:

Using String concatenation:31939 milliseconds

Using StringBuilder:27 milliseconds

Sample Code

System.Diagnostics.Stopwatch time = new Stopwatch(); string test = string.Empty; time.Start(); for (int i = 0; i < 100000; i++) {     test += i; } time.Stop(); System.Console.WriteLine("Using String contactenation: " + time.ElapsedMilliseconds + " milliseconds"); StringBuilder test1 new StringBuilder(); time.Reset(); time.Start(); for (int i = 0; i < 100000; i++) {     test1.Append(i); } time.Stop(); System.Console.WriteLine("Using StringBuilder: " + time.ElapsedMilliseconds + " milliseconds");

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » C# Code Optimization Using StringBuilder

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址