Immutability vs manual checking performance

85 views Asked by At

In a react native app using redux, I would like to update the state of the app with immutable-js. I'm using mergeDeep to update the state. There is one problem: when there has been removed an element from an array. So I'm detecting this case by converting the new data to immutable and then comparing sizes. This works fine:

function updateSettings(state, action) {
    const mutablePath = [].concat(action.path);
    const lastPathKey = mutablePath.pop();
    let nextState;
    let newArr;

    if (isInt(lastPathKey)) {
        // An array has been changed
        if (Immutable.fromJS(action.data).getIn(mutablePath).size < state.getIn(mutablePath).size) {
            // The element at lastPathKey has been removed
            newArr = state.getIn(mutablePath).remove(lastPathKey);
            nextState = state.setIn(mutablePath, newArr);
        }
    }

    if (!nextState) {
        nextState = state.mergeDeep(action.data);
    }

    return nextState;
}

The action.data is always the complete object path (as I'm using tcomb-form-native): If an element has been changed action path is like this:

action.path = ["testStruct", "deepArray", 0, "objectArr", "valDAOA1"]
action.data = {
    "isShowHelp": false,
    "testStruct": {
        "deepArray: [
            {
                "objectArr": {
                    "valDAOA1": 10
                }
            },
            {
                "objectArr": {
                    "valDAOA1": 20
                }
            }
        ]
    }
}

If an array element has been removed:

action.path = ["testStruct", "deepArray", 1]
action.data = {
    "isShowHelp": false,
    "testStruct": {
        "deepArray: [
            {
                "objectArr": {
                    "valDAOA1": 10
                }
            }
        ]
    }
}

I'm wondering if it would be more efficient to get the array size with manual method like proposed in https://stackoverflow.com/a/6491621/4025963 and if there are other cases wich should be taken in consideration.

0

There are 0 answers