Best js string builder

JavaScript performance comparison

Test case created by André Farzat


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

Preparation code

<script src="">
<script src="">
String.prototype.format = function(){
    var args = arguments;
    return this.replace(/\{(\d)\}/g, function(a,b){
        return typeof args[b] != 'undefined' ? args[b] : a;
Benchmark.prototype.setup = function() {
    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.";

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
JS normal concat
window.res = "<ul><li>" + window.t1 + "</li><li>" + window.t2 + "</li><li>" + window.t3 + "</li></ul>";
JS replace function
window.res = window.txt.replace('{0}', window.t1).replace('{1}', window.t2).replace('{2}', window.t3);
jquery validate format function
window.res = jQuery.validator.format(window.txt, window.t1, window.t2, window.t3);
String format function
window.res = window.txt.format(window.t1,window.t2,window.t3);

Compare results of other browsers


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:

1 comment

Mike commented :

Cool. Thanks for sharing. Would be interesting to see Internet Explorer results as well

Comment form temporarily disabled.

Add a comment