.NET Framework 2.0 Performance Inspection Questions - String Operations

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, Rico Mariani, and Alex Mackman



String Operation Inefficiencies

Review your code to see how it performs string manipulation. Intensive string manipulation can significantly degrade performance. Consider the following questions when reviewing your code's string manipulation:

  • Do you concatenate strings?
  • Do you use StringBuilder?
  • Do you perform string comparisons?
  • Do You Concatenate Strings?


If you concatenate strings where the number of appends is known, you should use the + operator as follows.


  String str = "abc" + "def" + "ghi";


If the number and size of appends is unknown, such as string concatenation in a loop, you should use the StringBuilder class as follows.


  for (int i=0; i< Results.Count; i++){
    StringBuilder.Append (Results[i]);
  }


Do You Use StringBuilder?

StringBuilder is efficient for string concatenation where the number and size of appends is unknown. Some of the scenarios which demonstrate an efficient way of using StringBuilder are as follows:

  • String concatenation


  //Prefer this 
  StringBuilder sb;
  sb.Append(str1);
  sb.Append(str2);
  //over this
  sb.Append(str1+str2);


  • Concatenating strings from various functions
  //Prefer this
  void f1( sb,…);
  void f2( sb,…);
  void f3( sb,…);


  //over this
  StringBuilder sb;
  sb.Append(f1(…));
  sb.Append(f2(…)); 
  sb.Append(f3(…));


Do You Perform String Comparisons?

Check whether your code performs case-insensitive string comparisons. If it does, check that it uses the following overloaded Compare method.


  String.Compare (string strA, string strB, bool ignoreCase);


Watch out for code that calls the ToLower method. Converting strings to lowercase and then comparing them involves temporary string allocations. This can be very expensive, especially when comparing strings inside a loop.

Personal tools