String concatenation: using += vs. using array push vs. unshift

JavaScript performance comparison

Revision 7 of this test case created

Info

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.

Preparation code

<script>
  var length = 1500;
  var html = [];
  var str = "";
</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
+=
str = "";
while (str.length < length) {
  str += '0';
}
pending…
push
str = "";
while (html.length < length) {
  html.push('0');
}
str = html.join("");
pending…
unshift
str = "";
while (html.length < length) {
  html.unshift('0');
}
str = html.join("");
pending…
push reverse
str = "";
while (html.length < length) {
  html.push('0');
}
html.reverse();
str = html.join("");
pending…
unshift reverse
str = "";
while (html.length < length) {
  html.unshift('0');
}
html.reverse();
str = html.join("");
pending…
fast push
str = "";
while (html.length < length) {
  html[html.length] = "0";
}
str = html.join("");
pending…
fast push reverse
str = "";
while (html.length < length) {
  html[html.length] = "0";
}
html.reverse();
str = html.join("");
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