String concatenation

JavaScript performance comparison

Revision 34 of this test case created

Info

Different ways to concatenate strings together

Preparation code

<script>
  var arr = ['a', 'b', 'c', 'd']

// The constructor initializes an Array
    StringBuilderEx = function()
    {
        this._buffer = new Array();
    }

    StringBuilderEx.prototype =
    {
    // This method appends the string into an array
        append : function(text)
        {
            this._buffer[this._buffer.length] = text;
        },
       
    // This method does concatenation using JavaScript built-in function
        toString : function()
        {
            return this._buffer.join("");
        }
    };

// Assigns our class to Array class
    var StringBuilderEx = Array;
   
    // Using prototype I link function append to push and toString to join
    Array.prototype.append=Array.prototype.push;
    Array.prototype.toString=Array.prototype.join;

</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Direct concatenation
var foo = arr[0] + arr[1] + arr[2] + arr[3];
pending…
Individual += statements
var foo = arr[0];
foo += arr[1];
foo += arr[2];
foo += arr[3];
pending…
Individual statements
var foo = arr[0];
foo = foo + arr[1];
foo = foo + arr[2];
foo = foo + arr[3];
pending…
Using Array#join
var foo = arr.join('');
pending…
Single individual statement
var foo = arr[0];
foo += arr[1] + arr[1] + arr[2];
pending…
Function based (for)
function concat(arr) {
  len = arr.length;
  for (s = "", i = 0; i < len; s += arr[i], i++);
  return s;
}

var foo = concat(arr);
pending…
Stringbuilder Class
var sb = StringBuilderEx();
sb.append(arr[0]);
sb.append(arr[1]);
sb.append(arr[2]);
sb.append(arr[3]);
var foo = sb.toString();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment