String concatenation (v97)

Revision 97 of this benchmark created on


Description

Different ways to concatenate strings together

Preparation HTML

<script>
  var str1 = "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefga";

  var str2 = "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg";

  var str3 = "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg";

  var str4 = "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg";

  var arr = [str1, str2, str3, str4];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Direct concatenation
var foo = "";
for(var i=0; i<1000; i++){
  foo += str1 + str2 + str3 + str4;
}
ready
Individual += statements
var foo = str1;
for(var i=0; i<1000; i++){
  foo += str2;
  foo += str3;
  foo += str4;
}
 
ready
Individual statements
var foo = str1;
for(var i=0; i<1000; i++){
  foo = foo + str2;
  foo = foo + str3;
  foo = foo + str4;
}
ready
Using Array#join
var foo = arr.join('');
var arr2 = [];
for(var i=0; i<1000; i++){
  arr2.push(arr.join(''));
}
var res = arr2.join('');
ready
Single individual statement
var foo = str1;
for(var i=0; i<1000; i++){
 foo += str2 + str3 + str4;
}
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
concat
var foo = str1;
foo = foo.concat(str2);
foo = foo.concat(str3);
foo = foo.concat(str4);
ready

Revisions

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