Sometimes over-optimizing jQuery causes script to run slower
Recently i wrote a new jQuery plugin i tried to optimize the code as much as possible.
Looking at these 2 snippets:
They return the same result.
Which one would be faster?
As you might know jQuery’s width() method returns the current computed width for the first element in the set of matched elements.
So I always thought why give jQuery the whole set just to get the first elements width, why not make it easier and pass only the first element in the collection by filtering the collection with .eq() to the width method.
It turns out that the width method itself handles it better.
See the results of the jsperf i put together.
The truth is, as @paulirish says “Don’t treat jQuery as a Black Box” always dig in to the source code and see what it does internally.
If you look in the jQuery’s fn.width source where you can see that jQuery filters out the first element the most native way it can and it does it right in the beginning of the function.
var elem = this;
Here are 2 videos in which paul digs into jQuery’s core.
Willing to optimize apps to run the fastest posible, developers can sometimes asume (mostly after reading posts amateur developers write) that some optimizations are really better practices. But unfortunately sometimes it might even slower your app. sometimes these optimization’s are just for edge cases, (for instance only where there are 1000′s of nodes to manipulate)…