String concatenation (v32)

Revision 32 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 = 'a' + 'b' + 'c' + 'd';
ready
Individual += statements
var foo = 'a';
foo += 'b';
foo += 'c';
foo += 'd';
ready
Individual statements
var foo = 'a';
foo = foo + 'b';
foo = foo + 'c';
foo = foo + 'd';
ready
Using Array#join
var foo = arr.join('');
ready
Single individual statement
var foo = 'a';
foo += 'b' + 'c' + 'd';
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('a');
sb.append('b');
sb.append('c');
sb.append('d');
var foo = sb;
ready

Revisions

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