Imagine we have a text field that executes the code below on each keydown event:

```
if( $('#my_input').val() == '' )
  $('#my_span').html('my input is blank');
else
  $('#my_span').html('My input is not blank');

```

Obviously we are executing code that possibly sets the state of something (`#my_span` element) to what it already is and this seems inefficient. But I am curious as to what the alternative is? Adding more checks like:

```
if ( $('#my_input').val() == '' ){
  if ( $('#my_span').html() != 'my input is blank' )
       $('#my_span').html('my input is blank');
}
else if ( $('#my_span').html() != 'My input is not blank' )
          $('#myspan').html('My input is not blank');

```

Is the latter more efficient? It would seem to me more 'correct', but obviously it's more code and I'm not sure how much more efficient it is than the first example. 

I know that the former always involves a DOM manipulation, which will factor in computing the relative efficiency, but I've encountered situations like this before in non-DOM related code, so wondering what is the best approach in all cases. Should you always do the extra check on the value of something before setting it to a new value?

**EDIT:**

My final version actually uses a combination of the answers here so thanks to all for the great replies. So to sum, I now:

* Cache the jquery objects in a closure
* Uses state to determine the assignment to a new state

Also as an aside, the setTimeout on the keydown is a very nice way to get a input fields value immediately. Thanks again.