jQuery performance: Chain appends or append multiple arguments?

211
April 24, 2018, at 09:51 AM

I was wondering which of those is more performant, and more importantly why?

$('a').append(
    $('<b></b>').text('1'),
    $('<b></b>').text('2'),
    $('<b></b>').text('3'));

and

$('a')
    .append($('<b></b>').text('1'))
    .append($('<b></b>').text('2'))
    .append($('<b></b>').text('3'));

where a and <b> are an arbitrary selector and tag. As far as I was able to tell from trying them out, they both function in exactly the same manner.

Relevant question: What is the best way to add options to a select from as a JS object with jQuery?

Edit:

The reason I was asking this question was to know whether I should structure appends as:

texts = ['1','2','3','4','5'];
$a = $('a');
$a.append(...texts.map(function(o){ return $('<b></b>').text(o); }));

or as:

texts = ['1','2','3','4','5'];
$a = $('a');
for (o in texts) {
    $a.append($('<b></b>').text(o));
}

The latter one is more intuitive, and I believe most programmers would choose to write it, when the earlier one performs better.

Answer 1

You can use a benchmarking tool to test this. I used JSPerf: https://jsperf.com/so-question

The results show that the first case is much faster. I believe it is because that jQuery does a lot of initialization, checking, and compatibility work every time you call a function that works with an element, that is, .append().

The first case only calls .append() once, whereas the second case calls .append() three times. In general, the less function calls you make, the faster your code will be.

READ ALSO
How to show menu on click rather than mouse hover with jquery and css?

How to show menu on click rather than mouse hover with jquery and css?

https://universaltechnologiescorpcom is my website

130
How to subtract 20 pixels from element&#39;s height with jquery?

How to subtract 20 pixels from element's height with jquery?

How to set the element's height then subtract by 20 pixels?

143
Continuously change the position of range input element on mouse down event (in single steps)

Continuously change the position of range input element on mouse down event (in single steps)

I'm trying to build a slider using range input element which displaces by 1 step on click, scroll or long press(continuous press)I have the logic required for click and scroll, however the same logic doesn't seem to be working on mouse down event (for long/continuous...

122
blocked event in jquery full calendar is not showing

blocked event in jquery full calendar is not showing

we have this project for bookings using jquery full calendar, instead of showing a blocked event with title bookings in month view see the link https://wwwscreencast

137