Thursday, November 23, 2006

Efficient String Concatenation in JS

In .NET, we use StringBuilder if we need to concatenate strings for better string manipulation performance. For instance,

StringBuilder builder = new StringBuilder();
builder.append("This");
builder.append("is");
builder.append("really");
builder.append("good");
builder.append("for");
builder.append("performance");

string str = builder.ToString();

In JS, we can also do the same thing for better memory allocation in string concatenation too.

var builder = new Array();
builder.push("This");
builder.push("is");
builder.push("really");
builder.push("good");
builder.push("for");
builder.push("performance");

var str = builder.join("");


This method will perform faster if the number of string concatenation is huge. THe normal += operator will win, otherwise.

Check Efficient JavaScript for more information on optimizing JS code

No comments: