Keith Davis wrote:
How should I expect the performance of this function to be?

[...snipped code suspected problem area...]
       * var $aTOC = document.getElementsByClassName('tocitem');*

Unfortunately the only way to find objects with a given class name can be slow. This is because the library much search each element in consideration and see if it contains the given class name. Since an element can have more than one class name this is not a simple comparison.

document.getElementsByClassName() uses a regular expression to find matching classes which is fairly fast but if you have a lot of elements it can be slow. The best way to make it faster is to reduce the number of element to check. For example if you know that the elements you are looking for is contained by an element with a known id you can do:

$$('#section .tocitem');

Or if you know the element tag name you can increase performance by searching elements with the known tag. So:

$$('li.tocitem');

One more problem to consider. If you use the $$() instead of document.getElementsByClassName() it will use Element.hasClassName() which is much slower than using a regular expression. So prior to using the $$() function you might want to do:

Element.hasClassName = function(element, className) {
        return element.className.match(new RegExp("(^|\\s)" +
                className + "(\\s|$)"));
};

This will cause Element.hasClassName() to use the same implementation that document.getElementsByClassName() uses which in my tests produces much better performance because it is a simple regex (builtin to Javascript and therefore fast) instead of splitting each classname, constructing an object and then iterating over each item in the collection to determine if the class exists.

Eric

_______________________________________________
Rails-spinoffs mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs

Reply via email to