Yahoo News with 1 second CSS Class Name lookups per page
The screenshot shows the calls to getElementsByClassName doing lookups for classes such as “yn-menu”, “dynamic-_ad” or “filter-controls”. Even though Firefox supports a native implementation of CSS class name lookups it seems that YUI 2.7 (which is used on this page) does not take advantage of this. When we drill into the PurePath for one of these calls we can see what these calls actually do and why it takes them about 150ms to return a result:
How to speed up these lookups?
There are two solutions to this specific problem: a) upgrade to a new version of YUI or b) specify a tag name additionally to the class name
Upgrade to newer library version
Framework developers have invested a lot in improving performance over the last couple of years. The guys from Yahoo did a great job in updating their libraries to take advantage of browser specific implementations. Other frameworks such as jQuery did the same thing. Check out the blogs from the YUI Team or jQuery. If you use a different framework I am sure you will find good blogs or discussion groups on how to optimize performance on these frameworks.
Coming back to YUI. I just downloaded the latest version of YUI and compared the implementation of getElementsByClassName from 2.7 (dom.js) and 3.3 (compat.js). There has been a lot of change between the version that is currently used at Yahoo News and the latest version available. Changing framework versions is not always as easy as just using the latest download as a change like this involves a lot of testing – but – the performance improvements are significant and therefore everybody should consider upgrading to newer versions whenever it makes sense.
Specify Tag Name additionally to Class Name
The following text is taken from the getElementsByClassName documentation from YUI 2.7: “For optimized performance, include a tag and/or root node when possible”
Why does this help? Instead of iterating through all DOM elements YUI can query elements by tag name first (using the native implementation of getElementsByTagName) and then only iterate through this subset. This works if the elements you query are of the same type. On all the websites I’ve analyzed the majority actually queries elements of the same type. Also – if you are just looking for elements under a certain root node specify the root node, e.g.: a root DIV element of your dynamic menus.
Conclusion: Stay Up-to-Date with your Frameworks
To sum this blog post up: follow the progress of the frameworks you are using. Upgrade whenever possible and whenever it makes sense. Also – stay up-to-date with blogs and discussion forums about these frameworks. Follow the framework teams on Twitter or subscribe to their news feeds.