javascript - Is there a cost to jQuerying an existing jQuery object? -


i'm wondering whether lazily doing $( ) without first checking whether something jquery instance has performance downsides?

the use case i'm thinking of function following:

function foo( element ){   var $element = $( element );   // $element... } 

if pass jquery instance function, re-wrapping jquery instance jquery instance? , have performance implications (say, on many iterations)?

foo( $( "#somediv" ) ); 

looking @ source code (v 2.1.4 of question), see jquery.fn.init checking selector that's passed it, , if it's not string, dom element or function, pass through jquery.makearray , return result.

so there doesn't appear explicit checking within jquery "constructor" short-circuits if selector jquery instance. matter?

makearray uses merge and/or push, there's bit of processing, significant?

all right, since seem never able walk away yak needs shaving, here's jsperf test, seems suggest checking , short-circuiting instead of (accidentally) re-wrapping jquery instance can improve performance 30%. in books, that's significant enough warrant uglier code.

here 2 tests:

function nocheck(element) {   var $element = $(element);    $element.css("color", "red"); }  nocheck($("#somediv"));  function shortcircuit(element) {   var $element = element instanceof jquery ? element : $(element);    $element.css("color", "red"); }  shortcircuit($("#somediv")); 

according jsperf, nocheck performs 30% slower shortcircuit

play around code in jsfiddle.

i'm not going accept answer while encourage additional perspectives / tests, etc.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -