Best js string builder

JavaScript performance comparison

Revision 6 of this test case created

Info

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

Preparation code

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

//
// StringBuilder class using join
//

// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value)
{
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value)
{
    if (value)
    {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.clear = function ()
{
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.toString = function ()
{
    return this.strings.join("");
}
</script>
<script>
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.";
};
</script>

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>";
pending…
JS replace function
var body = [];
body.push("<ul><li>", window.t1, "</li><li>", window.t2, "</li><li>", window.t3, "</li></ul>");
window.res = body.join("");
pending…
jquery validate format function
window.res = jQuery.validator.format(window.txt, window.t1, window.t2, window.t3);
pending…
String format function
window.res = window.txt.format(window.t1,window.t2,window.t3);
pending…
StringBuilder class using 'join'
// create a StringBuilder
var sb = new StringBuilder();

// append the text
sb.append(window.t1);
sb.append(window.t2);
sb.append(window.t3);

// get the full string value
var s = sb.toString();
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