Speeding up Prototype’s Selector

While working on the future AJAX interface of jamendo, I ran into some performance problems that were due to the extensive use of the new Prototype 1.5 function, $$. (Announcement of $$ on Ajaxian)

Prototype’s current code is quite elegant (as always!) but very slow, so I wrote an add-on that makes this function up to 20 times faster in most usual cases (tested on IE6, Firefox 1.5 and Opera). Don’t believe me, test it yourself!

Download the add-on | Stripped down version (1.3Kb) | Interactive test suite ** UPDATE:** Thanks to StoneCypher from #prototype I ran the regression tests and fixed a trivial bug. Now the add-on passes the regression tests! Good :-)

Here are the main ideas of this add-on:

  • Forwarding the call to the old $$ if the selector expression is too complicated (currently: if it uses attributes)
  • Replacing regular expressions with a simple parser
  • Minimizing the number of operations done on each iteration.
  • Trying to use getDocumentById() instead of getDocumentByTagName() when possible.
  • Avoiding recursive functions with return values.
  • Not being afraid of some “old-style” code if it speeds up the execution ;-)

I just emailed the code to Sam Stephenson (the author of Prototype), I hope he’ll welcome the speedup! I don’t know if this add-on could make it into the Prototype SVN trunk, maybe some comments from Sam or from readers of this blog will help improve it.

To use this code in your website, just include the javascript file after prototype.js, and the $$ function will be automatically replaced. The old one will still be available as “$$old” (but you shouldn’t need it. The add-on is “feature-compatible” with the original)

This code is released under the same license as Prototype (“AS-IS” ?) so feel free to use it. (In this case, a comment about our exciting free music website jamendo would be appreciated too ;-)

That’s it ;-) I look forward to having your comments on this code, it’s open for discussion!