Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 414
Jim G. Avatar asked Apr 22 '12 16:04

Jim G.


2 Answers

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.

like image 123
Sampson Avatar answered Nov 04 '22 07:11

Sampson


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

like image 20
Gordon Gustafson Avatar answered Nov 04 '22 06:11

Gordon Gustafson