Reputation: 12378
I was reading the dojo query tutorial and saw
// retrieve an array of nodes with the class name "odd"
// from the first list using a selector
var odds1 = query("#list .odd");
// retrieve an array of nodes with the class name "odd"
// from the first list using a DOM node
var odds2 = query(".odd", document.getElementById("list"));
and they explain that odds2 is faster than odds1 because odds2 searches for .odd in the #list dom rather than the whole html dom. What I'm wondering is what are the advantages of doing odds1 (other than cleaner code, i guess)? Because it seems to me for any case where query is searching for objects within an id element the odds2 style should always be used (assuming proper id, class html use), so why doesn't dojo automatically parse the query string in odds1 to call odds2?
Upvotes: 1
Views: 106
Reputation: 30416
Well looking at the code (http://svn.dojotoolkit.org/src/dojo/trunk/query.js for query and http://svn.dojotoolkit.org/src/dojo/trunk/selector/acme.js the default selector engine) it appears that the "big" performance improvements comes from the fact that the initial DOMNode List is reduced when you give the query method some help with the document.getElementById("list")
, however it appears you can just pass the query method a string of the parent node's id and achieve the same performance.
query(".odd", "list");
Then there is the fact that you can cache the DOMNode list by storing the result of document.getElementById("list")
in a variable and reuse it. However in general readability (in matters that are this trivial) tends to trump performance. Considering the number of problems that a bad JavaScript interpreter can hide, having readable code can end up saving you a lot of trouble.
Upvotes: 2