Lately more and more developers are focusing on performance and it is a new hype in the javascript development world to optimize Javascript code.

Developers these days do not only care that their app works in all browsers etc. They will go the extra mile and ensure that the code is optimized and that the javascript execution time is the fastest it can be.

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[0];

Here are 2 videos in which paul digs into jQuery’s core.

10 things i learned from the jquery source
11 more things i learned from the jquery source