Which of these jQuery JavaScripts will have better performance? - javascript

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

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!

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.

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.

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

Related

Does javascript run after HTML element css display:none executed?

I'm building a responsive site. But on the phones, it takes much time for loading to be done. I think it's because of javascript. On slow speed phones, executing javascript maybe a problem. So if I hide some elements (display: none) which will be handled by javascript, will all scripts for those elements be executed as normal or any way else?
Maybe this is a bad question but someone please explain how javascript works in this case.
Yes, unless you're using the :visible selector, jQuery will still find elements styled with display:none which are in the DOM.
JavaScript can still see those elements.
There are a lot of things that can hurt performance on phones, and there are a lot of things that can be done to help make it better (shallow CSS selectors, events delegation, off-DOM manipulation, restructuring JS to be modular, and lazy-loading it onto a page, .png optimization for images, concatenation and compression of JS/CSS, object pools for memory-management)...
A lot of things to squeeze more performance out of phones...
But "display:none" isn't going to stop JS from seeing or using those elements, and if you're doing a lot of query-selector stuff:
$("#my-div .my-span").each("...");
It's going to keep right on doing it.
Display being set to none on an HTML element does not prevent JavaScript from being executed on it. Otherwise it would be troublesome to show and/hide elements with JavaScript.
To speed up your site, there are a number a techniques that can be used. Many are dependent on your situation. It sounds like you may benefit from late loading the JavaScript, i.e. moving it to the bottom of the body tag. Doing this will allow your page to render prior to loading all of the JavaScript.
Google's PageSpeed may help guide you to other ways of improving your page load time.
https://developers.google.com/speed/docs/insights/about

which is one more expensive to call? showing-hiding a dom node or creating-deleting a dom node

Which is one more expensive to call?
showing-hiding dom node or
creating-deleting dom node
Assume there is only 1 dom or a few (less than 5) nodes that we need to manipulate and the application runs on desktop.
For a small number, does it even matter at all?
How about for mobile applications?
The difference between the two will be infinitesimally small for only a few elements -- it could absolutely be considered negligible.
That being said, showing and hiding the element via CSS will be faster unless you use jQuery's .show() and .hide(). jQuery's .hide() is much slower than any other method of hiding an element. If you'd like to know why, read the "Why is .hide() slower?" section at the bottom of my answer.
Anyway, you should make your decision based on which method suits your needs best. If you don't ever need the element again, you may as well delete it. If you just wan't to hide it for a little while or under certain conditions, show/hide it.
But if you want to test it yourself, here ya go :)
Why is .hide() slower?
jQuery's .hide() is basically the same as using .css('display','none') except that it caches the previous value of the display style, so that when you call .show(), your element will be correctly reverted to look the exact same as it did. If it had display:inline, it'll have it when it gets re-shown. If it had display:block, it'll have display:block. This can be pretty useful.
Here's an example:
lets say we have a div with id="myDiv" and it is styled in an external file with display:inline. We want to hide it.
With the .css way, we'd do this:
$('#myDiv').css('display','none');
and then later on sometime, one of your fellow developers wants to show it again under certain conditions. He'll have no idea what the display property should be, since the css is in an external file somewhere. Most developers default to display:block, like this:
$('#myDiv').css('display','block');
However in this case, we'd get a totally different style, since it was originally inline. A clever developer will have no problem figuring out what went wrong, but not all developers are clever :)
With .show() and .hide(), this becomes a non issue. We don't care what style it used to have. We just want it to be back where it was, and that's exactly what it'll do.

Is there an efficiency difference between finding by id and finding by class with JavaScript/jquery?

Is there an efficiency difference between finding by id and finding by class with JavaScript/jquery?
Is one better than the other? If so is it because indexes of ID or Class are made in the DOM somewhere?
Does it end up not mattering much?
Finding by ID is always faster, no matter where (getElementById(), $('#id'), or even in regular CSS).
Since ID's are unique per page, they're much faster to find.
In addition, when using $('#id'), jQuery will map that back to the built-in getElementById(), which is the fastest way to query the DOM.
Well, logically speaking, an ID would be more efficient, as there is (should be) only one of it, so once it finds it, it will stop searching. However I am not familiar with the jQuery source, I don't know how it actually works, that's from a logic perspective.
For most browsers, the difference in speed between searching by id and searching by class name depends on how many elements have a given class. At best, there will be only one such element, and the search speed ought to be the same. At worst, there are a bazillion elements with a given class. Typically, though, you shouldn't have to worry about the speed of searching through 10-20 elements containing the same class.
A critical caveat, though: MSIE <= 8 has no native getElementsByClassName, so jQuery has to fall back to a full DOM tree search unless, e.g., the element name of the wanted element is also provided. Even then. $('div.myclass') may not be much help if your document is large and exceedingly div-happy. Benchmarking is really the only way to find out.

optimizing jQuery Selectors - Which is faster?

Are selectors or functions faster in jQuery? Example:
$('#something div.else'); // find multiple divs with class .else
or
$('#something').children('div.else');
I'm trying my best to optimize a page with hundreds of returned elements that seems to hang on a certain crappy computer here in the office (that must use Internet Explorer ::shudder::).
Well in this case, the second's faster, but, they're not equivalent. The first finds any descendant div.else, the other finds only direct children that are div.else.
It depends on your DOM as to which is faster, the equivalent of the second would be this:
$('#something > div.else');
This uses the child selector. They should be very, very close, and in any case, I doubt a selector descending from an ID is your problem area, I think you'll find the vast majority of your time in JS is spent elsewhere.
For diagnosing speed issues, get a profiler, for IE specifically there's a fantastic free one called dynaTrace AJAX Edition. Grab it, follow the short tutorials on their site...you'll find where your pain areas in IE are pretty quickly.
Although I haven't checked with the jQuery code, I think the difference should be negligable between your two examples - although the first one should run a little faster.
The problem with old IE versions is that they do not support a native way to fetch items based on class names. In this case, jQuery has to execute a regulra expression on each class attribute of each element contained.
If it is possible in your case, you might gain quite a lot performance when being able to select on an unusual tagname:
$("#container blockquote.else")
and ideally,leave away the class name.
EDIT: just saw the answer from Nick and he's right, the scond one only has to check the direct children. The equivalent first one would be:
$("#container > div.else")
In your specific example, your first example of
$('#something div.else');
gets optimized through Sizzle (which is delivered within the jQuery lib) into
$('#something').find('div.else');
without that optimization, it would be slower, since the selector engine sizzle does work from right to left. So, it would match all divs with the class else and would then check which of those has #something as parent.
edit
The Sizzle optimazation is slower
anyway, since it took a while until
that task is completed and some
functions are called on the way
In general, using jQuery functions is a lot faster. For instance jQuerys .eq() function will use an array slice to reduce a wrappet set of jQuery objects, whereas :eq() selector will invoke sizzle.
If in your example, div.else elements are direct children of #something, .children() will beat .find() since .find() will also lookup all descendants (and their childs).
If I understand correctly you need the fastest way to get #something div.else in IE6. Since jQuery uses Sizzle, the way it will find that is first find all div's, then filter by the ones with the else class, and has an ancestor with the #something id.
Your second example will be faster if it contains few children, slower if it contains many.
A suggestion you could try would be to use another tag type instead of div, one that isn't used in your page, say blockquote. Just reset it's styles with css so it looks like a normal div, then change your selector to #something blockquote.else which should be tons faster.

Good ways to improve jQuery selector performance?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I'm looking for any way that I can improve the selector performance of a jQuery call. Specifically things like this:
Is $("div.myclass") faster than $(".myclass")
I would think it might be, but I don't know if jQuery is smart enough to limit the search by tag name first, etc. Anyone have any ideas for how to formulate a jQuery selector string for best performance?
There is no doubt that filtering by tag name first is much faster than filtering by classname.
This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName.
In some cases, you can speed up a query by limiting its context. If you have an element reference, you can pass it as the second argument to limit the scope of the query:
$(".myclass", a_DOM_element);
should be faster than
$(".myclass");
if you already have a_DOM_element and it's significantly smaller than the whole document.
As Reid stated above jQuery is working from the bottom up. Although
that means $('#foo bar div') is a
lot slower than $('bar div #foo')
That's not the point. If you had #foo you wouldn't put anything before it in the selector anyway since IDs have to be unique.
The point is:
if you are subselecting anything from an element with an ID then select the later first and then use .find, .children etc.: $('#foo').find('div')
your leftmost (first) part of the selector can be less efficient scaling to the rightmost (last) part which should be the most efficient - meaning if you don't have an ID make sure you are looking for $('div.common[slow*=Search] input.rare') rather than $('div.rare input.common[name*=slowSearch]') - since this isn't always applicable make sure to force the selector-order by splitting accordingly.
In order to fully comprehend what is faster, you have to understand how the CSS parser works.
The selector you pass in gets split into recognizable parts using RegExp and then processed piece by piece.
Some selectors like ID and TagName, use browser's native implementation which is faster. While others like class and attributes are programmed in separately and therefore are much slower, requiring looping through selected elements and checking each and every class name.
So yes to answer your question:
$('tag.class') is faster than just $('.class'). Why?
With the first case, jQuery uses the native browser implementation to filter the selection down to just the elements you need. Only then it launches the slower .class implementation filtering down to what you asked for.
In the second case, jQuery uses it's method to filter each and every element by grabbing class.
This spreads further than jQuery as all javascript libraries are based on this. The only other option is using xPath but it is currently not very well supported among all browsers.
Here is how to icrease performance of your jQuery selectors:
Select by #id whenever possible (performance test results ~250 faster)
Specify scope of your selections ($('.select', this))
I'll add a note that in 99% of web apps, even ajax heavy apps, the connection speed and response of the web server is going to drive the performance of your app rather than the javascript. I'm not saying the you should write intentionally slow code or that generally being aware of what things are likely to be faster than others isn't good.
But I am wondering if you're trying to solve a problem that doesn't really exist yet, or even if you're optimizing for something that might change in the near future (say, if more people start using a browser that supports getElementsByClassName() function referred to earlier), making your optimized code actually run slower.
Another place to look for performance information is Hugo Vidal Teixeira's Performance analysis of selectors page.
http://www.componenthouse.com/article-19
This gives a good run down of speeds for selector by id, selector by class, and selector prefixing tag name.
The fastest selectors by id was: $("#id")
The fastest selector by class was: $('tag.class')
So prefixing by tag only helped when selecting by class!
I've been on some of the jQuery mailing lists and from what I've read there, they most likely filter by tag name then class name (or vice versa if it was faster). They are obsessive about speed and would use anything to gain a smidgen of performance.
I really wouldn't worry about it too much anyway unless you are running that selector thousands of times/sec.
If you are really concerned, try doing some benchmarking and see which is faster.
Consider using Oliver Steele's Sequentially library to call methods over time instead of all at once.
http://osteele.com/sources/javascript/sequentially/
The "eventually" method helps you call a method after a certain period of time from its initial call. The "sequentially" method lets you queue several tasks over a period of time.
Very helpful!
A great tip from a question I asked: Use standard CSS selectors wherever possible. This allows jQuery to use the Selectors API. According to tests performed by John Resig, this results in near-native performance for selectors. Functions such as :has() and :contains() should be avoided.
From my research support for the Selectors API was introduced with jQuery 1.2.7, Firefox 3.1, IE 8, Opera 10, Safari 3.1.
If I am not mistaken, jQuery also is a bottom up engine. That means $('#foo bar div') is a lot slower than $('bar div #foo'). For example, $('#foo a') will go through all of the a elements on the page and see if they have an ancestor of #foo, which makes this selector immensely inefficient.
Resig may have already optimized for this scenario (it wouldn't surprise me if he did - I believe he did in his Sizzle engine, but I am not 100% certain.)
I believe that selecting by ID first is always faster:
$("#myform th").css("color","red");
should be faster than
$("th").css("color","red");
However, I wonder how much chaining helps when starting with the ID? Is this
$("#myform").find("th").css("color","red")
.end().find("td").css("color","blue");
any faster than this?
$("#myform th").css("color","red");
$("#myform td").css("color","blue");

Categories

Resources