Warning: Unfortunately the jsperf, that would be the most practical tool to test what I say in my reply, has had stability problems, and I’m having trouble using it at the moment. So consider that some of my arguments can be either confirmed or disproved by a real performance test. And don’t forget that the best option may vary according to the browser.
To understand the possible performance bottlenecks in these code snippets, let’s see what operations they perform:
$(...)
- Creates an array of jQuery objects containing all elements that fit the past selector. Whenever possible jQuery uses the native function document.querySelectorAll
for that reason.
.hide()
- Loop over our array of elements, hiding them all, one by one.
.attr('nome', valor)
- Executes another loop over the array, setting the attribute value for all of them, one by one.
The difference between your two code snippets is in the operation 1, but may impact the other two.
In theory, select only the elements of a class (such as ".produto"
) is faster than selecting the elements of this class that meet any additional criteria (such as ".produto[invisible=false]"
). But this may depend on how the selection algorithm is implemented in each browser. And, also in theory, selecting attributes is slower - which also depends on the implementation.
But assuming that the first selector is actually faster, and the other operations (the loops) are the same in the two snippets of code that you posted, then the first version is faster than the second, right? Not necessarily! The first version has the potential to select more page elements, since it is less restrictive than the second, and this can influence the execution time of the loops.
Imagine a page with many products (I don’t know, 5,000), but only 10 visible. The first version can even select faster, but it will select 5,000 elements, and then iterate over those 5,000 elements twice. Already the second would select only 10 elements, and make 2 loops on these 10, which theoretically is much faster and can compensate for the greater slowness of selection.
Completion
In performance issues like this, the only way to do a realistic test is to reproduce all the conditions of your application, and see how each variation behaves. What matters is how they behave in these situations, not in any possible situation. And if you test the two variations in your application, with real users, on the various browsers that you intend to support, and both of them turn out well, forget about the performance issue. The cost (in time, effort) of micro-optimizations of this type is much higher than the performance improvement they may provide, and that is generally negligible.
Following this idea of using a class for
visible
and another toinvisible
gained 2 seconds of performance at the time of executing code :D– Silvio Andorinha