>> The thread about benchmarks got me thinking about compilation and
>> caching of selectors too. It could be a big win for benchmarks where
>> they use the same selector in a loop 1000 times! :-)
> The problem with caching is that it's unable to handle situations
> where the DOM changes in-between, unless there's an explicit
> .refreshCache() or some such. And doing this by default is hardly
> desirable, as it would cause a lot of common code to break.
Like Mark said, we're not caching the DOM results, but compiling and caching
a custom function to *return* the DOM results.
jQuery.find = function(s,c) {
c = c || document;
var f = jQuery.$cache(s);
// If the function is cached, just run it
if ( f )
return f(c);
// Not cached; compile, cache, and run the function
...
};
A cached function for $("p, #id1, #id2 .test") might be:
function(c) {
return $.unique( // return node array, duplicates and nulls removed
c.getElementsbyTagName("p"),
document.getElementById("id1"),
$.getClass(document.getElementById("id1"), "test")
);
}
The first time the selector is run you take the hit on compiling the
function, but after that you're running at maximum speed. Unfortunately, I
can't think of any way to eliminate the costly tree-crawling to find classes
or other complex relationships, and you'd still need $.unique in most cases
to ensure that there aren't any duplicate nodes. (It could be skipped on
selectors like $("div, p") or $("[EMAIL PROTECTED], textarea") where no
element can possibly be duplicate, but you'd still need to combine the two
nodelists.)
So my take was that the performance payback for simple selectors called
frequently could be good, but those cases are already pretty fast--we're
reducing a number that's already small. Complex selectors would still
require helper functions or compiled-in loops on every function invocation,
so they won't be improved nearly as much. Still, it would be a fun project
to try!
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/