[EMAIL PROTECTED] wrote:
Thanks - I'm finding the selectors method a lot slower than both "The
Ultimate" version and Prototype's getElementsByClassName, at least for
pages with large DOMs.
I would imagine they can be slower because they are so capable but there
are a few tips you can keep in mind that can help performance.
* Do what you can to limit class comparisons. Doing a class comparison
is an expensive operation. To test if an element has a matching class
the Selectors use Element.hasClassName() which is expensive because it
must parse the class attribute (split on spaces) and then do a linear
search. This makes the overall search for matching elements a O(N^2)
operation. Element.hasClassName() could probably have it's performance
improved by using a regular expression like
document.getElementsByClassName() does, but it will never be cheap
because searching for a matching class will always involve a linear
search through a list of possible DOM elements (keeping it still a O(N)
operation).
* Also limit the number of attribute comparisons. Finding elements with
matching attributes also is an expensive operation. Doing a single
comparison is not expensive (an O(1) operation) but a linear search of
all possible elements must still be done making the overall process an
expensive operation (O(N)).
* Use ID selectors to narrow your search field. For example "#news
.item" is much faster than just ".item" (assuming your document is
constructed so that those queries return the same results). This is
because it first finds the #news DOM Element using
document.getElementByID() (which is browser implemented and therefore
fast) and then only does the linear search on all child nodes of #news
for the matching elements. This can greatly reduce the number of class
comparisons.
* If you know the tag name for matching elements use it even if it is
not necessary for finding the elements you are after. This is because
the Selectors use document.getElementsByTagName() to reduce the number
of elements considered (which is a browser implemented function and
therefore fast).
* Combine methods of improving performance. For example:
".delete" - Really Slow
".item .delete" - Slow
"#news .item .delete" - Faster
"#news tr.item .delete" - Even faster
"#news tr.item a.delete" - Blazing
Take a look at the source for the Selectors. It is a little dense but
understanding how it will work will help you keep your application
responding smoothly while still keeping your code very readable.
Eric
_______________________________________________
Rails-spinoffs mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs