Blog

Benchmarking .append() vs .appendTo()

Consider these two lines of code, both of which do the exact same thing:

I'd been using these pretty much interchangeably, until I realized that one is probably more efficient than the other. Benchmark time! After starting with an empty <div class='primary'>, I executed the following loop to get a good sample:

Then I did the same thing with .append():

The difference was pretty striking. Here are the results of three page loads (in milliseconds):

.appendTo()

CHROME: 1250/1140/1130
FF: 2918/3611/2637
SAFARI: 743/770/750

.append()

CHROME: 1729/1368/1484
FF: 4758/4805/6224
SAFARI: 725/1029/958

10 points for Gryffindor .appendTo()! That's a difference of nearly an entire second, averaged among all browsers. Combined with the other hundreds of lines of JS that your site is running, it seems that using .appendTo to create and attach DOM elements is the way to go.