Reputation: 72729
I've done a test with performance of a jQuery selector.
The two selectors I have tested:
selection_width = total_width - ($('#commands .minimap').outerWidth() + $('#commands .actions').outerWidth());
And:
var commands = $('#commands');
selection_width = total_width - ($('.minimap', commands).outerWidth() + $('.actions', commands).outerWidth());
The second one is way faster than the first one. Is this correct or did I screw up the test somewhere?
Upvotes: 1
Views: 94
Reputation: 8454
In the first test, jQuery uses document.querySelectorAll()
(relatively fast) twice. In the second case, jQuery uses document.getElementById()
(very fast) once and document.getElementsByClassName()
(fast since you declared a context) twice.
Upvotes: 2
Reputation: 9455
The first statement has to analyze the complete DOM tree and look for the element #commands
twice, whereas the second one only needs one check over the whole DOM tree. The search for the elements .minimap
and .actions
is faster because for that, jQuery only has to iterate the children of #commands
, and not the whole document.
Upvotes: 1
Reputation: 150313
In the second one you store the commands element so it's not searched again. Thus you get better performance.
Upvotes: 1