'Jquery - Append vs AppendTo

Can somebody explain me why regular Append into a loop works better than AppendTo?

//Using Regular Append
var ul = $("<ul></ul>");
$("#myDiv").empty().append(ul)

$.each(movies, function (count, item) {
    var id = 'li_' + count;
    ul.append('<li id=' + id + '>' + item + '</li>');

    $('#' + id).click(function () { });
});

//Using AppendTo
var div = $("#myDiv").empty(),
    ul = $("<ul></ul>").appendTo(div);

$.each(movies, function (count, item) {
    $('<li>' + item + '</li>').click(function () { }).appendTo(ul);
});

Result http://jsperf.com/sdp-jquery-append/3



Solution 1:[1]

append vs appendTo performance (jQuery 1.9.1)

From what can be seen in jQuery code, one of the reasons appendTo has better performance, is because appendTo implementation is slightly more complicated than regular append.

While append depends roughly on native appendChild function, appendTo is a jQuery addition which needed to be handled by code (there's additional loop inside appendTo which operates on elements and actually calls .append again). While the performance hit isn't big (if you just compare simplest usage, like in this example: http://jsperf.com/sdp-jquery-append/5), it certainly is something to keep in mind.

As to example labeled "Better" in linked jsperf:

It performs better, because in fastest version (in jsperf you linked to) you just collect html to be appended, instead of actually appending it on every iteration.

It saves browser resources, since it don't have to reflow and repaint the content on every iteration.

Solution 2:[2]

append(content) appends content to the inside of every matched element.

appendTo(selector) appends all of the matched elements to another specified set of elements.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 nstCactus