Flex Optimization Tip: Evaluate Your Setter Parameter

Flash Builder makes it easy to generate getters and setters from a variable definition. Just select the variable, right-click and choose Source > Generate getters/setters.

The generated code is simple; the getter returns the value and the setter sets the value:

private var _myData:String;

public function get myData():String {
    return _myData;
}

public function set myData(value:String):void {
   _myData = value;
}

Oftentimes in Flex, however, changing a variable is a trigger that causes other code to run or update. But why would you want this extra processing to occur if the value that is being assigned hasn’t changed?

Instead, add a quick comparison:

public function set myData(value:String):void {
    if(_myData != value) {
       _myData = value;
    }
}

Note that you would use ObjectUtil.compare rather than equality to compare complex Objects:

public function set myObjectData(value:Object):void {
    if(ObjectUtil.compare(_myObjectData,value) != 0 ) {
       _myObjectData = value;
    }
}

Obviously, depending on the complexity and size of the objects, and the amount of work to be done after an update, comparing Objects may not make sense in all circumstances. That’s a judgement call you can make based on your particular code.