- Use StringBuilder instead of string variable in case of concatenations.
C# Code (Wrong) | C# Code (Correct) |
String xXml = “”; | // make sure that the StringBuilder capacity is large enough for the resulting text StringBuilder oSB = new StringBuilder(165); for (Int32 nRep = 1; nRep <= Reps; nRep++) { oSB.Append("<Order orderId=""); oSB.Append(nRep); oSB.Append("" orderDate=""); oSB.Append(DateTime.Now.ToString()); oSB.Append("" customerId=""); oSB.Append(nRep); } |
Note:
- Use + When the Number of Appends Is Known or Fixed (String str = str1+str2+str3)
- The StringBuilder class starts with a default initial capacity of 16. Strings less than the initial capacity are stored in the StringBuilder object.
- Use the Overloaded Compare Method for Case-Insensitive String Comparisons as shown below.
C# Code (Wrong) | C# Code (Correct) |
// Bad way for insensitive operations because ToLower creates temporary strings | str.Compare(str, str2, false); |
Useful links on string:-
- “Improving String Handling Performance in .NET Framework Applications” http://msdn2.microsoft.com/en-us/library/aa302329.aspx
- “Chapter 5: Improving Managed Code Performance” http://msdn2.microsoft.com/en-us/library/ms998547.aspx#scalenetchapt05_topic26
- "Concatenating Strings Efficiently", http://www.yoda.arachsys.com/csharp/stringbuilder.html
No comments:
Post a Comment