22 November 2006

javascript StringBuilder

i've seen way too many cases of developers using string concatenation in javascript, especially directly on the innerHTML property of some DOM node. here's a javascript StringBuilder that should give you the same sort of boost you might find in java or c#.

function StringBuilder() {
this._strings = [];
this.append = function(s) { this._strings.push(s); };
this.toString = function() { return this._strings.join(''); };
}
it uses the built-in speed of the join and push methods and avoids the constant re-allocation of memory. i'm betting it's faster, too.

No comments:

Post a Comment