Redundant comparison & "if" before assignment

In a winforms control we had set the BackgroundColor to a specific color:

myControl.BackgroundColor = Color.White

Under specific circumstances this could happen in a tight loop and lead to a frozen UI. After some performance analysis we found that this call was the reason for the frozen UI and so we simply changed it to:

if (myControl.BackgroundColor != Color.White)
    myControl.BackgroundColor = Color.White

And the performance of our tool was back on track (and then we eliminated the reason of the tight loop).

So this check is not always redundant. Especially if the target is a property which does more within the setter then simply applying the value to a backing store.


Here is a code sample when the check is quite useful:

 public class MyClass {
    ...
    int ageValue = 0;

    public int AgeValue {
      get {
        return ageValue
      }
      protected set {
        ... // value validation here

        // your code starts
        if (value != ageValue) { 
          ageValue = value; 
        }
        // your code ends
        else
          return; // do nothing since value == ageValue

        // ageValue has been changed
        // Time (or / and memory) consuming process
        SaveToRDBMS();
        InvalidateCache(); 
        ...
      } 
    } 

 ... 

More natural implementation, however, is to check in the very beginning in order to avoid unnecessary computation.

    protected set {
      if (ageValue == value)
        return;

      ... // value validation here
      ageValue = value; 

      // ageValue has been changed
      // Time (or / and memory) consuming process
      SaveToRDBMS();
      InvalidateCache();  
      ...
    }