String concatenation

JavaScript performance comparison

Revision 5 of this test case created by Juan Mendes

Info

Testing string concatenation methods in straight code and abstracted in a StringBuilder

Preparation code

<script type="text/javascript">

var CONST = {
    STR_PART: 'Hello Diggity Dog more more more more more more more more more more more more more more more more more more more',
    ITERATIONS: 30
};

function StringBuilderConcat() {
  this._str = "";
}

StringBuilderConcat.prototype.append = function (str) {
    this._str += str;
}

StringBuilderConcat.prototype.toString = function () {
  return this._str;
}

function StringBuilderArrayPush() {
    this._array = [];
}

StringBuilderArrayPush.prototype.append = function (str) {
    this._array.push(str);
}

StringBuilderArrayPush.prototype.toString = function () {
  return this._array.join('');
}

function StringBuilderArrayIndex() {
  this._array = [];
  this._index = 0;
}

StringBuilderArrayIndex.prototype.append = function (str) {
    this._array[this._index] = str;
    this._index++;
}

StringBuilderArrayIndex.prototype.toString = function () {
  return this._array.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
Array index - No Abstraction
var build = [];
for (var i=0; i < CONST.ITERATIONS; i ++) {
  build[i] = CONST.STR_PART;
}
var out = build.join('');
pending…
Array push - No abstraction
var build = [];
for (var i=0; i < CONST.ITERATIONS; i ++) {
  build.push(CONST.STR_PART);
}

var out = build.join('');
pending…
Straight String Concat - No abstraction
var build = "";
for (var i=0; i < CONST.ITERATIONS; i ++) {
  build += CONST.STR_PART;
}
 
pending…
StringBuilder - Array index
var builder = new StringBuilderArrayIndex();
for (var i=0; i < CONST.ITERATIONS; i ++) {
  builder.append(CONST.STR_PART);
}
var out = builder.toString();
pending…
StringBuilder - Array push
var builder = new StringBuilderArrayPush();
for (var i=0; i < CONST.ITERATIONS; i ++) {
  builder.append(CONST.STR_PART);
}
var out = builder.toString();
pending…
StringBuilder - string concat
var builder = new StringBuilderConcat();
for (var i=0; i < CONST.ITERATIONS; i ++) {
  builder.append(CONST.STR_PART);
}
var out = builder.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