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
Post a Comment