What's faster when using jQuery to check visibility, $.data() or $.is(':visible')?
Today while I was writing some code for two methods that shows and hides a menu, I made a small test to see the most efficient way to check the visibility of the menu.
The results varied from a browser to another, FF 4.0b12 is faster using $.data
, but Chrome (webkit) and Opera is faster when using $.is(':visible')
.
I couldn't test on IE9 , because the browser kept locking on me! Here is the test case: http://jsperf.com/data-or-display/3
So, what's the most efficient way to check visibility WITH jQue开发者_如何学Cry ?
$('whatever').is(':visible')
reads the best. I think that is what matters. Unless you need to check hundreds of elements a second, I would not waste my time.
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"
Donald Knuth
Source (PDF)
If you must get the best performance, ditch jQuery and use native JavaScript.
Because is(':visible')
also tests the visibility of ancestors, it will be faster to test data
on elements.
It is also faster to use data('hidden')
than attr('data-hidden')
as the boolean values are stored as booleans and not converted to/from strings.
Updated JSPerf: http://jsperf.com/data-or-display/5
For the specific test case I also added a basic .toggle()
, so that all the iteration and checking was done by jQuery, but that was still slightly slower than using an each
and testing data. I am guessing this is a similar reason to attr
being slower than data
and toggle()
checking attributes (e.g. for display: none
).
精彩评论