Looking at improving the performance of my jquery selectors. so any tips or articles as the best per formant jquery selectors? For example selecting the a div's id. Anywhere online I can provide html and compare the different selectors I can use to select the required element.
You can compare selector performance here: http://jsperf.com/
Just setup your HTML, include jQuery and place each selector you want to compare as a test case.
Many of the rules here still apply, however the game changed a bit in jQuery 1.4.3+, after that Sizzle (jQuery's selector engine) will use querySelectorAll() in browsers that support it.
This article goes into some detail about jQuery selectors and their performance. It's mainly about using jQuery the right way. Since a lot of jQuery use revolves around selectors, the article spends some time on them.
Basically a few things to remember:
If you're looking for performance, use selectors that delegate to native DOM-inspection methods (getElementById, getElementsByTagName)
Cache results
Pseudo-selectors can cause a performance hit.
One thing these articles don't address is what your starting point is. If you are starting with the entire DOM tree, then these articles are actually useful.
However, if you have an element to start with, it then depends on what your search is. Most of my dynamic javascript with MVC templates tends to grab the element on which the action is taken, then do a search for parent objects. This eliminates the need to uniquely name a container when they are randomly generated-- makes things a lot easier from a dynamic devlopment standpoint.
While searching for a near-parent node may not be as fast as searching for an ID, the performance should be negligible compared to the amount of time and/or performance of generating and tracking a number of unique IDs.
As with everything in development, "it depends" will reign here.
I notice a lot of these type of questions are restricted to performance comparison between different jQuery selectors.
I recently came across an article that compares jQuery selectors against their native Javascript counterparts.
It might sound like a lot of hassle, but the performance gain is quite substantial. More than I imagined actually.
Article:
http://www.sitepoint.com/jquery-vs-raw-javascript-1-dom-forms/
Related
I have an idea for a web application for which I would require full control over the functionality of the embedded text editors and the text editors must function exactly the same across all browsers. The standard contenteditable functionality is not sufficient to my needs on this occasion.
So I have been experimenting with various ways to implement a custom text editor. My first approach was to detect mouse clicks for caret insertion (though with no visible caret since there doesn't appear to be a way to achieve this). This worked rather well, but unfortunately there was no way to display the caret (aka flashing I-beam).
This means that my flashing caret must also be custom made. I can only think of two good ways to achieve this in a way which will be compatible across all browsers.
The first (and probably better) option would be to implement a custom layout engine in JavaScript much like Google have done with Google Docs.
The second solution (probably a lot easier) would be to encapsulate each character within its own <span> element and thus allowing the faux caret to be placed between specific characters. This does mean that there will be a LOT of span elements, but this would certainly achieve what I need whilst taking advantage of the browser layout engine. Another benefit with this approach is that I do not need to rely upon dodgy browser-specific text selection hacks.
So my question, is option #2 a really bad idea? If so, why?
First of all - do you really need to work on your own editor? There are Firepad and Etherpad with their pretty cool collaborative editing and perhaps more open source editors not based on contenteditable. It's really hard to create such editor, so it does not make sense to waste time on it.
However, if you really want to work on your own solution and you need exactly the same behaviour across all browsers, then you're doomed ;). Even if you'll avoid contenteditable there are definitely other things that can go wrong.
Anyway, the answer:
First option is very hard and time consuming at the beginning but it gives you a lot more power than the second one. E.g. having completely custom layout engine, you'll be able to implement page breaks without waiting for the CSS3's implementation (on which you will never could rely on, because you want exactly the same behaviour across all browsers). And in fact, you'll be able to bypass most of browsers' rendering differences. But, unless you've got a team of decent JS devs and few months (at least), I wouldn't even start thinking about that.
The second solution - reusing DOM is more realistic. I would perform some performance tests first, but having span per character would be easy to find out where the caret should be placed after mouse click. Without that it requires some trick... Which I don't know. You can try to check how Etherpad and Firepad (which uses Ace code editor) deal with that, but still - wrapping will be the easiest choice and at least on decent browsers it should not cause performance issues, unless you want to edit really long documents (but then you can start some optimizations).
I always romoving 'current' class of all siblings then add 'current' class to my clicked one. I want to know will it be faster only removing 'current' class of which has 'current'.seems to be a simple question, but I really want to know.
Yes, filtering the query to a smaller set of elements will perform faster, because there are less elements to check.
In modern browsers, jQuery will use native methods to query the DOM, so adding the selector has a negligible performance impact.
I don't think there's much difference, since there's only one "current". It doesn't matters too much for querying one more element or one less.
Usually I'll first find out the outer element to narrow down
$('#selectionDiv').find() ....
Depending on how many elements you are re-classing, the impact of the optimization will of course vary.
I tested it, http://jsperf.com/reclassing-all-or-one, using 7 (seemed reasonable for for example navigation tabs) divs and I think the difference was significant (reclassing all 30% slower than only one), percentage wise. If one cares about actual time though it may not be, but I can't really see any reason not do be distinct.
I currently have code that is pulling in data via jQuery and then displaying it using the each method.
However, I was running into an issue with sorting, so I looked into using, and added, jQuery's filter method before the sort (which makes sense).
I'm now looking at removing the sort, and am wondering if I should leave the filter call as-is, or move it back into the each.
The examples in the jQuery API documentation for filter stick with styling results, not with the output of textual content (specifically, not using each()).
The documentation currently states that "[t]he supplied selector is tested against each element [...]," which makes me believe that doing a filter and an each would result in non-filtered elements being looped through twice, versus only once if the check was made solely in the each loop.
Am I correct in believing that is more efficient?
EDIT: Dummy example.
So this:
// data is XML content
data = data.filter(function (a) {
return ($(this).attr('display') == "true");
});
data.each(function () {
// do stuff here to output to the page
});
Versus this:
// data is XML content
data.each(function () {
if ($(this).attr('display') == "true") {
// do stuff here to output to the page
}
});
Exactly as you said:
The documentation currently states
that "the supplied selector is
tested against each element [...]",
which makes me believe that doing a
filter and an each would result in
non-filtered elements being looped
through twice, versus only once if the
check was made solely in the each
loop.
Through your code we can clearly see that you are using each in both cases, what is already a loop. And the filter by itself is another loop (with an if it for filtering). That is, we are comparing performance between two loops with one loop. Inevitably less loops = better performance.
I created this Fiddle and profiled with Firebug Profiling Tool. As expected, the second option with only one loop is faster. Of course with this small amount of elements the difference was only 0.062ms. But obviously the difference would increase linearly with more elements.
Since many people are super worried to say the difference is small and you should choose according to the maintainability, I feel free to express my opinion: I also agree with that. In fact I think the more maintainable code is without the filter, but it's only a matter of taste. Finally, your question was about what was more efficient and this is what was answered, although the difference is small.
You are correct that using filter and each is slower. It is faster to use just the each loop. Where possible do optimise it to use less loops.
But this is a micro optimisation. This should only be optimised when it's "free" and doesn't come at a cost of readable code. I would personally pick to use one or the other based on a style / readability preference rather then on performance.
Unless you've got a huge sets of DOM elements you won't notice the difference (and if you do then you've got bigger problems).
And if you care about this difference then you care about not using jQuery because jQuery is slow.
What you should care about is readability and maintainability.
$(selector).filter(function() {
// get elements I care about
}).each(function() {
// deal with them
});
vs
$(selector).each(function() {
// get elements I care about
if (condition) {
// deal with them
}
}
Whichever makes your code more readable and maintainable is the optimum choice. As a separate note filter is a lot more powerful if used with .map then if used with .each.
Let me also point out that optimising from two loops to one loop is optimising from O(n) to O(n). That's not something you should care about. In the past I also feel that it's "better" to put everything in one loop because you only loop once, but this really limits you in using map/reduce/filter.
Write meaningful, self-documenting code. Only optimise bottlenecks.
I would expect the performance here to be very similar, with the each being slightly faster (probably noticeable in large datasets where the filtered set is still large). Filter probably just loops over the set anyway (someone correct me if I'm wrong). So the first example loops the full set and then loops the smaller set. The 2nd just loops once.
However, if possible, the fastest way would be to include the filter in your initial selector. So lets say your current data variable is the result of calling $("div"). Instead of calling that and then filtering it, use this to begin with:
$("div[display='true']")
I generally don't worry about micro-optimizations like this since in the grand scheme of things, you'll likely have a lot more to worry about in terms of performance than jQuery .each() vs. .filter(), but to answer the question at hand, you should be able to get the best results using one .filter():
data.filter(function() {
return ($(this).attr('display')==="true");
}).appendTo($('body'));
For a primitive performance comparison between .each() and .filter(), you can check out this codepen:
http://codepen.io/thdoan/pen/LWpwwa
However, if all you're trying to do is output all nodes with display="true" to the page, then you can simply do as suggested by James Montagne (assuming the node is <element>):
$('element[display=true]').appendTo($('body'));
I'm working on a JavaScript (using HTML as display tech) widget framework for an embedded device where memory consumption is a big deal.
Recently I tried to create a table-layout using only DIVs. But to mimic the colspan and rowspan functionality it became quite complicated, adding extra logic to make it all dynamic.
The result came out quite good layout-wise, but at the cost of too much memory consumption (had to have several JS objects representing each cell and then a DIV as presentation)
Wouldn't it be better to just use the TABLE element instead, getting the col- and rowspans and layout for free? Especially since all markup is crated by the framework and that the user (of the framework) never actually touches the HTML itself.
Or am I missing something here?
well tables are perfectly fine for tabular data if you want to do it right semantically.
And imo, you have to go for the best solution in your situation. Performance is more important than using div's or not in this case i guess.
If you start out with the mentality of "I need a table-layout", it's inevitable that you'll end up deciding that you need to use a <table>, because CSS cannot deliver on the subtleties of colspans and rowspans. But do you need a table-layout? You don't describe the underlying layout requirements, so it's impossible for us to steer you either to or from <table> except in broad generalities.
Go ahead and use a table. One of the main reasons that CSS layouts are encouraged is accessibility (probably you don't care about). Another reason is separating content from layout - you are probably creating both. So, the disadvantages of tables are of very low importance compared to the advantages in your case.
Here's my problem: I'm writing a WordPress plugin that helps budding CSS authors see how css applies to their theme in real time. It's got a numer of nifty features, except one, which is pretty crucial in my mind.
I want to allow them to click an element, see the full selector path to that element (that part is done), and then show them which styles in their stylesheet apply to it.
I have the full selector path to the element (html body div#page div#post-18.post h2.posttitle, for example), and I have their stylesheet parsed into individual selectors - but I can't figure out any way to compare the two. Some ideas I've had:
Use jQuery, and run every selector (in the stylesheet) to see what it returns. I'm not crazy abou tthis because it seems like a huge performance drag to check (potentially thousands) of selectors against the full DOM. On top of that, I've then got to compare the jQuery objects to see if they're pointing at the same thing - and based on what I've read about comparing objects, I'm not sure that will be a walk in the park.
Write my own, simple comparing function, and compare the full selector path with the css selector. I was pretty sold on this, until I started thinking about the various advanced selectors - : > etc.
Use sizzle (or similar), or somehow use jQuery's implementation of sizzle to just compare the selectors. They're running these selectors against the DOM, so surely they have the ability to just compare selector strings? Somehow?
I'm stuck. Any help is greatly appreciated.
Checking for equality in that complex structures (like CSS) is extremely difficult (e.g. you cannot determine this by testing for equal result sets, since they could behave entirely different under other circumstances). You might be able to figure this out using browser-specific APIs if they are available in JavaScript (e.g. Firebug displays stylesheets that affect the selected elements). Other than that, your first approach is the only possible one AFAIK.