0

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.

mmdts
  • 757
  • 6
  • 16

1 Answers1

2

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

enter image description here

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.

apscience
  • 7,033
  • 11
  • 55
  • 89
  • Just to make sure I get this right, the reason is that `append(a,b,c)` just checks the validity of `$('a.test')` once, while `.append(a).append(b).append(c)` has to check it thrice? – mmdts Apr 24 '18 at 01:17
  • Correct, yes. You'll save even more time by doing `.append('123')` too for example – apscience Apr 24 '18 at 01:19
  • 1
    The numbers are just an example. .text() is used specifically to allow for something like .text('') not adding a child element. – mmdts Apr 24 '18 at 01:24
  • Thanks a lot. Edited my question to reflect why I was asking a seemingly useless question. :) – mmdts Apr 24 '18 at 01:43