Is it worthwhile to check the visibility of a DOM element before toggling its visibility? Or is this premature optimization?

StackOverflow https://stackoverflow.com/questions/10269629

Question

Please consider the following jQuery code:

if ($(this).is(':hidden')) {
    $(this).show();
}

My Question:

  • Is it worthwhile to check for the element's visibility before issuing the show() command?
    • i.e. Are DOM writes more expensive than DOM reads, and does this pattern include a small performance optimization?
  • Or is the visibility check of no utility, and would it be cleaner code to simply, unconditionally, issue the show() command?
Was it helpful?

Solution

If you want it shown, I wouldn't bother checking to see if it's hidden - I would just show it. I would assume there would be a small perf advantage to not doing the conditional check to begin with, but I'm also confident it may be pretty negligible.

I've created a performance test which indicates no checking results in an 25% faster execution. You can view this online (and test it in a few browsers) at http://jsperf.com/is-hidden-check.

OTHER TIPS

Aside from giving you an extremely minimal increase in speed at best, its possible this might not even always behave as you want it to:

Source:

How :hidden is determined was changed in jQuery 1.3.2. An element is assumed to be hidden if it or any of its parents consumes no space in the document. CSS visibility isn't taken into account (therefore $(elem).css('visibility','hidden').is(':hidden') == false).

Checking for visibility is not incredibly complex, but IMHO even this excerpt shows it is not exactly trivial. While you could deal with the issue of making sure your visibility check works properly while using :hidden every time you want to make sure this code is working correctly, you could just forget the 5 milliseconds that you might have a chance at saving and instead save yourself the time spent to understand the code and check the documentation every time there might be a problem with this area.

Just use plain old show(); if there was a reason to do a check beforehand, I'm confident that the good ol' folks who make jQuery would have either provided a recommendation to do so in the docs somewhere or just hardcoded the check into the show method/ :D

your visibility check may be save some efforts because it will not issue the .show() if it's not really hidden.

So i think go with it

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top