Search code examples
jqueryoptimizationvisibilitypremature-optimization

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?

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.