I will outline some techniques that have worked for me in building good jQuery plugins.
- Cache your selectors. Not caching can be a real performance killer, once you select an element, cache it, if you plan to use it again. Even ID selectors should be cached. it will always be faster to reuse a cached selector than to ask the DOM for it. When it comes to plugins, you can hide the cached selectors in the main closure, and reuse them in the methods of the plugin.
- Cache your state. It will always be faster to check if a boolean is true, than to check if a DOM element is visible. Forget about the DOM. Cache everything you will need access to, cache your modifications. DOM access is slow. I will exchange a few bytes of memory for a few ms of execution any day.
- Use closures. If you dont know how to use closures, you must learn now. You wont be able to write a good plugin if you dont know when and how to use these. You should use the closure to hide all your config data, your cached selectors etc.
- Dont use $.fn. if it doesnt make sense. Sometimes it makes sense to return something other then the jQuery object from your plugin. You can always pass in the 'this' the old school way as an argument. Sometimes it may be better to return an object that makes some methods from the closure 'public' and exposes some members. This kind of an object can be useful when writing unit tests, or if you want to provide a rich API without bastardizing $.fn.
- Break things up into responsibilties. Let each method inside your plugin handle one thing. Do we need to recalucate something on window resize? Do we need to reload some event handlers after AJAX calls? Dont make one giant 'reload' method when you can have more specific methods that will save time.
- Time and profile. I wish i had started doing this earlier. Use firebug's timing and profiling to see which portions of your code are slow, and optimize them.
- Unit test. QUnit is jQuery's testrunner. Use it.
- Test on a Pentium 3, in IE 6. This is my golden standard. If its fast here, you have nothing to worry about.