Thoughts from the office by Ed Ball
Tuesday, October 14, 2003

In .NET, strings are immutable, so string concatenation always creates a new string. If you perform many such concatenations, in a loop, for example, such that the string gets very long, this can become very inefficient. Hence the StringBuilder class in System.Text, which allows, among other things, more efficient concatenation of strings.

Since JScript (JavaScript, ECMAScript) strings are also immutable, the scripting language has the same efficiency problems. While there's no StringBuilder object defined for JScript, you can use an array of strings as a poor man's StringBuilder. Instead of concatentating to a string, push to a string array. Then, when you need the big string, call join("") on the string array, which is considerably faster than the traditional approach.

// very slow
var strSlowText = "";
for (var nSlow = 1; nSlow < 10000; nSlow++)
  strSlowText += nSlow + " ";
 
// very fast
var astrFastText = [];
for (var nFast = 1; nFast < 10000; nFast++)
  astrFastText.push(nFast + " ");
var strFastText = astrFastText.join("");

I didn't invent this technique, of course, though I don't remember where I first read about it.

10/14/2003 4:38:00 PM (Pacific Daylight Time, UTC-07:00) | Comments [0] | Code#
Search
Archive
Links
Categories
Administration
Blogroll