String concatenation (v34)

Revision 34 of this benchmark created on


Description

Different ways to concatenate strings together

Preparation HTML

<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

Ready to run.

Testing in
TestOps/sec
Direct concatenation
var foo = arr[0] + arr[1] + arr[2] + arr[3];
ready
Individual += statements
var foo = arr[0];
foo += arr[1];
foo += arr[2];
foo += arr[3];
ready
Individual statements
var foo = arr[0];
foo = foo + arr[1];
foo = foo + arr[2];
foo = foo + arr[3];
ready
Using Array#join
var foo = arr.join('');
ready
Single individual statement
var foo = arr[0];
foo += arr[1] + arr[1] + arr[2];
ready
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);
ready
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();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.