Which of these lines is more efficient (CPU / memory) when executed in jQuery?

I have two scenarios. In each scenerio, tell me which version does the same thing more efficiently (for example, uses less CPU or memory):

The first scenario:

/*version 1*/
    $('body').append('#something');
/*version 2*/
    $('#something').insertAfter('body > *:last-child');

Second window:

/*version 1*/
    $('#something').method1();
    $('#something').method2();
    $('#something').method3();
/*version 2*/
    var $reference = $('#something');
    $reference.method1();
    $reference.method2();
    $reference.method3();

So, in each scenerio, which version is more efficient?

+3
source share
3 answers

In the first scenario, the first is more efficient, since it $("#someid")ultimately makes up a call document.getElementById, which is a call to its own code. Identifier selectors are pretty cheap compared to class selectors. The challenge $('body > *:last-child')will be a much more challenging challenge for SizzleJS.

, document.getElementById .

+3

, , ...

, . , .

+3
$('#something').method1().method2().method3();

if you do not plan to reuse the object, then do

var $ref = $('#ref');
$ref.method1().method2().method3();
+2
source

All Articles