Hi-performance Javascript Tips #2

Create your own version of Java’s StringBuilder:

var StringBuilder = function (str) {
    var _stack = str ? [str] : []; // str == initial string to start, if any
    // append can take one or more strings as arguments
    this.append = function () {
        _stack.push.apply(_stack, arguments);
        return this;
    this.toString = function (separator) {
        return _stack.join(separator || '');

This routine runs up to 8x faster in IE6 than normal string concatenation using the + and += operators! In IE7, I’ve clocked a 4x improvement.

Firefox 3.0 gets about a 20% speed boost. Safari 4 and Chrome get less than a 10% speed boost.

It would be an easy exercise to modify the StringBuilder class’ append method and constructor to take an existing StringBuilder object instead of a string.

3 thoughts on “Hi-performance Javascript Tips #2

  1. Would be interesting to see your test case too. I got no speed bust using this :

    start=new Date()
    for (i=0;i<1000000;i++) s+='Hello World'
    end=new Date()
    document.writeln('string ',end.getTime()-start.getTime())

    start=new Date()
    sb=new StringBuilder()
    for (i=0;i<1000000;i++) sb.append('Hello World')
    end=new Date()
    document.writeln('StringBuffer ',end.getTime()-start.getTime())

    And the results :

    - FireFox 3.0.10 :
    string 991
    StringBuffer 10177

    - SeaMonkey 1.1.16 :
    string 2611
    StringBuffer 16216

    - Opera 9.64 :
    string 816
    StringBuffer 4510

    - Midori 0.1.6 :
    string 1773
    StringBuffer 2332

  2. Hi,

    How did you test the functions for the speed comparison?

    I compared your method, the + and += operators, and the native String.concat() function, but in all browsers the .contact function beats the other methods of string concatenation.

    Results for 10000 repetitions:
    StringBuilder += String.concat()
    IE6 94ms 531ms 16ms
    IE7 110ms 672ms 15ms
    IE8 63ms 15ms 16ms
    FF3 43ms 5ms 4ms

    In Firefox 3.0 and IE8 the + and += operators perform even better than your function in my test, your function only performs better in IE6 and IE7.

    But I only used a simple loop to concatenate strings, so I was curious about how you got your test results.

  3. @Sjonner
    Never mind the .concat function, I made an error in the test, it is about as fast as the += operator, only in IE6 + 7 it is slower.

Comments are closed.