简体   繁体   中英

jQuery/JavaScript efficiency comparison when using a conditional vs. omitting it

Description of Problem:

Let's say I want to hide an element using jQuery.hide() . In this example, I want to hide #some_div no matter what when the constructor is clicked. So then, should I check whether it's visible to begin with, or should I simply omit the conditional altogether?

Example:

$('#button').click(function() {
  if ($('#some_div').is(':visible')) {
    $('#some_div').hide();
  }
}

...versus...

$('#button').click(function() {
    $('#some_div').hide();
}

It seems like a toss-up. If the DIV is only showing half the time, then half the time it won't need to hide it. Then again, the other half of the time it will need to perform the comparison in the conditional and hide it.

So which is better practice? And which is more efficient/faster to execute?

Seems like just hiding is faster than testing first: http://jsperf.com/testing-visibility-vs-just-hiding

That being said, it is very unlikely that this will be a bottleneck for your application. So, I suggest that you write the code that feels more natural to you, and start doing these micro-optimizations if you find out that it too slow. Most of the time, it won't matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM