I have a function to show or hide a certain UI control. In my example case below, the framework is jQuery I'm using for an event to show a tool tip that may fire a LOT (based on mouse movements) - but the underlying problem is more general and may also arise in a similar manner in lots of other UI frameworks. In fact, the problem could be even more generalized to any kind of component with two states to be switched often, not just UI components.Consider:Code A:$(this).plothover(function(item) {    if(item&&item!=undefined){      show tooltip   }   else      remove tooltip});Code B:$(this).plothover(function(item) {    if(item&&item!=undefined){      show tooltip   }   else {      if(tool tip is shown){           remove tooltip      }   }});item will exist at defined Cartesian points where datapoints exist (ie, graph coordinates on a canvas).  In other words, the odds are ~10000:1 in the favor of the else condition firing on a DPI basis.As the mouse moves, Code A removes it with no regard to any conditionCode B only removes it if it was already created, but has to test the creation firstSo, which is considered 'right'?Blind hide the control whether it is visible or not, or only hide it if it is visible?I've benchmark'ed it through jsperf and the differences are negligible performance wise but does lean towards the blind destroy.  But if it's 'wrong' by theory to do it, i'd rather chose the best practice route.--- EDIT ---To clarify, The actual invocation is not important (ie, how is it removed). Nor am I looking for a code review. The above given example is one of many times I've run into this case.   Rather, I wish to discuss the theory involved in Destroy what may exist or search and destroy if it exists.
Test & remove, or always remove
algorithms
Here's my post from Code Review I posted before the question got closed there:Why test in the first place? When you are trying to avoid an expensive operation, one that is significantly more expensive than the test itself.Your performance gain comes from selectively calling remove and gaining the time not spent always removing it.So your answer is, given 2 actions, test and remove, and p the probability of the tooltip being shown, test and remove when time(remove) > time(test) + p * time(remove).Which is exactly why how it's being removed matters.