Example Analysis of StringBuilder usage in. NET and stringbuilder usage
This example describes the usage of StringBuilder in. NET. Share it with you for your reference. The specific analysis is as follows:
Why use StringBuilder?
Why do we need to start with the features of the string object when using StringBuilder.
When a string object is concatenated, a copy of the string object is copied for operation each time because of its immutability, and its own string remains in the memory, A large number of temporary fragments may cause performance loss that cannot be ignored. Therefore, we recommend that you use StringBuilder when splicing a large number of strings.
Simple use of StringBuilder:
Copy codeThe Code is as follows: string s1 = "33 ";
String s2 = "44 ";
String s3 = "55"; // The requirement is to concatenate s1 s2 s3. This is a typical String concatenation.
// Use StringBuilder without generating useless temporary strings.
StringBuilder sb = new StringBuilder ();
// Splicing method 1
Sb. Append (s1 );
Sb. Append (s2 );
Sb. Append (s3 );
// Splicing method 2
// Because the Append () method returns a this, that is, the object itself. You can use this method.
// This method is commonly used in chained programming Jquery.
Sb. Append (s1). Append (s2). Append (s3 );
// Finally, just put sb. ToString.
PS: The AppendLine () method can automatically add a carriage return.
I hope this article will help you with the. net program design.