String concatenation: using += vs. using array push vs. unshift (v22)

Revision 22 of this benchmark created on


Description

Tests the performance difference of using two different ways of concatenating strings. The two TCs produce the same string result.

See http://jsperf.com/forloop-vs-reverse-while-loop-and-array-reverse/9 for array reverse vs custom loops.

See http://jsperf.com/array-push-reverse-vs-unshift-reverse for array push reverse vs. unshift reverse.

Setup

var length = 500;
    // String includes space separator, so double the total length to be equivalent.
    var lengthForStr = length * 2;
    var arr = [];
    var str = "";

Test runner

Ready to run.

Testing in
TestOps/sec
concat
while (str.length < lengthForStr) {
  str = str.concat(" x");
}
ready
push
while (arr.length < length) {
  arr.push("x");
}
str = arr.join(" ");
ready
unshift
while (arr.length < length) {
  arr.unshift("x");
}
str = arr.join(" ");
ready
push reverse
while (arr.length < length) {
  arr.push("x");
}
arr.reverse();
str = arr.join(" ");
ready
unshift reverse
while (arr.length < length) {
  arr.unshift("x");
}
arr.reverse();
str = arr.join(" ");
ready
fast push
while (arr.length < length) {
  arr[arr.length] = "x";
}
str = arr.join(" ");
ready
fast push reverse
while (arr.length < length) {
  arr[arr.length] = "x";
}
arr.reverse();
str = arr.join(" ");
ready
+=
while (str.length < lengthForStr) {
  str += " x";
}
ready

Revisions

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