Example Analysis of StringBuilder Usage in.NET

  • 2021-06-28 09:06:40
  • OfStack

The usage of StringBuilder in.NET is illustrated with examples.Share it for your reference.Specific analysis is as follows:

Why use StringBuilder

Why use StringBuilder starts with the nature of the string object.
When the string object is stitching strings, because of the invariance of strings, each time the string object is stitched, a copy will be copied out to perform the operation, while its own string remains in memory, and a large number of temporary fragments will cause an indispensable performance loss.StringBuilder is recommended for large number of string splicing
Simple ways to use StringBuilder:

string s1 = "33";
string s2 = "44";
string s3 = "55"; // The need is to s1 s2 s3 Stitch together in 1 Get up.This is 1 Typical string stitching.
// Use StringBuilder Does not produce a useless temporary string.
StringBuilder sb =new StringBuilder();
// Stitching method 1
sb.Append(s1);
sb.Append(s2);
sb.Append(s3);
// Stitching method 2     
// because Append() Method returns 1 individual this That is, the object itself.So you can use this method.
// Chain programming   Jquery This is commonly used
sb.Append(s1).Append(s2).Append(s3);
// Finally put sb.ToString()1 That's it.

The PS:AppendLine() method automatically adds a carriage return.

I hope that the description in this paper will be helpful to your.net program design.


Related articles: