Best js string builder (v2)

Revision 2 of this benchmark created by PAEz on


Description

Try to figure out the best way to build strings in javascript.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js">
</script>
<script>
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d)\}/g, function(a, b) {
      return typeof args[b] != 'undefined' ? args[b] : a;
    });
  }

  String.prototype.formatReplace = function() {
    var args = arguments,
        i = args.length - 1;
    var result = this;
    while (i >= 0) {
      result = result.replace('{' + i + '}', args[i]);
      i--;
    }
    return result;
  }

</script>

Setup

window.txt = "<ul><li>{0}</li><li>{1}</li><li>{2}</li></ul>";
    window.t1 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";
    window.t2 = "Aliquam tincidunt mauris eu risus.";
    window.t3 = "Vestibulum auctor dapibus neque.";
    window.ar1 = ["<ul><li>", "</li><li>", "</li><li>", "</li></ul>"];
    window.ar2 = ["Lorem ipsum dolor sit amet, consectetuer adipiscing elit.", "Aliquam tincidunt mauris eu risus.", "Vestibulum auctor dapibus neque."];

Test runner

Ready to run.

Testing in
TestOps/sec
JS normal concat
window.res = "<ul><li>" + window.t1 + "</li><li>" + window.t2 + "</li><li>" + window.t3 + "</li></ul>";
ready
JS replace function
window.res = window.txt.replace('{0}', window.t1).replace('{1}', window.t2).replace('{2}', window.t3);
ready
jquery validate format function
window.res = jQuery.validator.format(window.txt, window.t1, window.t2, window.t3);
ready
String format function
window.res = window.txt.format(window.t1, window.t2, window.t3);
ready
Something else
var z = 0;
window.res = [];
for (i = 0; i < window.ar2.length; i++) {
  window.res[z++] = window.ar1[i];
  window.res[z++] = window.ar2[i];
}
window.res[z] = window.ar1[i];
window.res.join('');
ready
Something else 2
window.res = '';
for (i = 0; i < window.ar2.length; i++) {
  window.res += window.ar1[i];
  window.res += window.ar2[i];
}
window.res += window.ar1[i];
ready
String format function using Replace
window.res = window.txt.formatReplace(window.t1, window.t2, window.t3);
ready

Revisions

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