string concatenation or adding dom

JavaScript performance comparison

Test case created by JulienW

Preparation code

<div id='container'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    var arr = [],
        urlbase = "http://www.somegallery.fr/image/",
        $container = $("#container");
   
    for (var i = 0, l = 100; i < l; i++) {
       arr.push(urlbase + i);
    }
};

Benchmark.prototype.teardown = function() {
    $container.empty();
};
</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
append on dom
var $ul = $("<ul>");
$container.append($ul);

    $.each(arr, function(count, item) {
        var newImg = '<li><img src="'+item+'"></li>';
        $ul.append(newImg);
    });
pending…
string concatenation
var tmp = ''; 
$.each(arr, function(count, item) {
    tmp += '<li><img src="'+item+'"></li>';
});
$container.append(tmp);
pending…
append on unattached dom with string concatenation
var $ul = $("<ul>");

    $.each(arr, function(count, item) {
        var newImg = '<li><img src="'+item+'"></li>';
        $ul.append(newImg);
    });

$container.append($ul);
 
pending…
USE THIS: append on unattached dom without string concatenation
var $ul = $("<ul>");

    $.each(arr, function(count, item) {
        var $img = $('<img>').attr('src', item);
        var $li = $("<li>").append($img);
        $ul.append($li);
    });

$container.append($ul);
 
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