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

3

5

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?
Prot answered 22/4, 2012 at 16:11 Comment(1)
Wrapping the object twice isn't going to help performance. You could use $MyElement = $(this) and then manipulate $MyElement to help performance.Villasenor
C
6

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.

Cabalism answered 22/4, 2012 at 16:13 Comment(1)
nice one,i also tested via your test case and really it save the timeMonosome
D
2

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

Delia answered 22/4, 2012 at 16:27 Comment(0)
M
0

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

Monosome answered 22/4, 2012 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.