Detecting which properties have been changed from two objects I have the following code. Providing two objects cmd and this.xxx.properties, script detects the only property changed and mutate the input object (cmd).

Script works fine but I would like to know if I could optimize or improve my code for speed.

    _deltaProperties: function (cmd) {

        var dataBefore = this.xxx.properties,
            newData = {};
        for (var prop in cmd.properties) {
            var newValue = cmd.properties[prop],
                oldValue = dataBefore[prop];
            if (newValue !== oldValue) {
                newData[prop] = cmd.properties[prop];
            }
        }
        cmd.properties = newData;
        return cmd;
    },
I did a bit of testing on jsperf which seems to indicate that it would be marginally faster for you to delete the properties you don't need rather than create a new object and replace it. Obviously, your mileage may vary. My test was objects with 6 properties, 3 of which were different.

EDIT : Delete is faster on IE. The new object version is faster on Chrome and FF.

_deltaProperties: function (cmd) {
    var prop;
    for (prop in cmd.properties) {
        if (cmd.properties[prop] === this.xxx.properties[prop]) {
            delete cmd.properties[prop];
        }
    }
    return cmd;
},


If you decided to keep your current code, there are some improvements you could make in terms of styling:

// I personally dislike underscores in variable names
deltaProperties: function (cmd) {
    // JavaScript only has function scope, a lot of developers define all 
    // variables at the top of the function - can help with subtle scope bugs
    var dataBefore = this.xxx.properties,
        newData = {},
        prop,
        newValue,
        oldValue;

    for (prop in cmd.properties) {
        newValue = cmd.properties[prop],
        oldValue = dataBefore[prop];
        if (newValue !== oldValue) {
            // Use newValue rather than accessing member again
            newData[prop] = newValue;
        }
    }
    cmd.properties = newData;
    return cmd;
},