Evanss
Evanss

Reputation: 23213

Which of these jQuery JavaScripts will have better performance?

I have sections with headers. Clicking the header collapses and expands the section below it. A class is also applied or removed to the header for styling purposes. There are 9 of these sections and headers.

$('.header').click(function() {
        $(this).toggleClass('open');
        $(this).next().slideToggle();
});

Im trying to improve performance for mobile devices. I dont mean page loading times, rather the smoothness of the animation and delay after touching the header before the annimation fires.

Ive read that using IDs is faster than Classes. How much faster will the following be? (note, it would need to be repeated 9 times and ive shown the first 2). Im also assuming using an ID is faster than traversing the DOM with .next(), how much difference will this make?

$('#header1').click(function() {
        $(this).toggleClass('open');
        $('#section1').slideToggle();
});

$('#header2').click(function() {
        $(this).toggleClass('open');
        $('#section2').slideToggle();
});

Note, I know its a bit of a crutch but I want to use jQuery not plain JavaScript. The jQuery library will be loaded anyway as its used elsewhere on the site. Thanks

Upvotes: 2

Views: 72

Answers (4)

Paystey
Paystey

Reputation: 3242

Technically:
The ID reference method is a far faster DOM lookup in browsers that don't support getElementByClassName. But that's offset by having to parse twice the amount of code and apply two click handlers. .live() may be faster still as it only binds to the body and does the lookup later.

Practically:
Very negligible difference. This is micro optimization territory. There are probably much bigger factors of speed in your code than this.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337743

The second method will be marginally quicker, however the slight gain will be negated by the ugliness and unmaintainability of the code.

Use the first option.

Upvotes: 1

Andrew Hall
Andrew Hall

Reputation: 3073

An id as a selector is quicker, but for maintainability do you really want that duplicated code?

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318808

It doesn't matter at all. While ID lookups are indeed the fastest, modern browsers have optimized selector-based lookups so all of them are pretty fast unless you do something that requires iterating over the whole document (such as a [someattribute] selector).

However, $('.header') saves you from repeating code and thus is the way to go. Besides that, it's more readable - in the second example you don't even know where the element it affects is without looking at the DOM.

So, instead of trying to optimize what doesn't need to be optimized, keep your code clean and maintainable!

Upvotes: 2

Related Questions