First, using + to create strings in JS is fine because there is no alternative.

But in C# and ASPX (and Java), string objects are “immutable”, which means you can’t alter their properties; when you use +, a whole new string is created to contain the two original pieces. So when you use a chain of +’s, you’re creating a lot of objects and then throwing them away.

Instead, use StringBuilder.Append or AppendFormat.  For example, change

  s = “[” + s + “]”;

to

//10 is an estimate of the final # of chars
  StringBuilder sb = new StringBuilder(10);
  sb.Append(”[”);
  sb.Append(s);
  sb.Append(”]”);
  s = sb.ToString();

or

  //10 is an estimate of the final # of chars
  StringBuilder sb = new StringBuilder(10);
  sb.AppendFormat(”[{0}]”, s);
  s = sb.ToString();

Note that this means you don’t want + inside your calls to Append, either.

Trackback URL
Leave your own comments about this post:
You must be logged in to post a comment.