Skip to content

Commit

Permalink
Optimize computed props
Browse files Browse the repository at this point in the history
An attempt to optimize computed props, by improving
comparison of inputs & by checking if the value needs an update.

The value comparison uses a naive comparison of of the JSON stringified values.

This will support more complex inputs & avoid unneccessary updates for complex results (arrays, objects).

related to ctrlplusb#732
  • Loading branch information
jmyrland authored and ctrlplusb committed Sep 15, 2022
1 parent 67b9aaf commit 9d7f95d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/computed-properties.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { areInputsEqual } from './lib';
import { areValuesEqual } from './lib';

export function createComputedPropertyBinder(parentPath, key, def, _r) {
let runOnce = false;
Expand All @@ -14,7 +14,7 @@ export function createComputedPropertyBinder(parentPath, key, def, _r) {
);
if (
runOnce &&
(areInputsEqual(prevInputs, inputs) ||
(areValuesEqual(prevInputs, inputs) ||
(_r._i._cS.isInReducer &&
new Error().stack.match(/shallowCopy/gi) !== null))
) {
Expand All @@ -24,7 +24,12 @@ export function createComputedPropertyBinder(parentPath, key, def, _r) {
return prevValue;
}
prevInputs = inputs;
prevValue = def.fn(...inputs);

const newValue = def.fn(...inputs);
if(!areValuesEqual(newValue, prevValue)) {
prevValue = newValue;
}

runOnce = true;
return prevValue;
},
Expand Down
4 changes: 4 additions & 0 deletions src/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,10 @@ export function areInputsEqual(newInputs, lastInputs) {
return true;
}

export function areValuesEqual(newValue, lastValue) {
return newValue === lastValue || JSON.stringify(newValue) === JSON.stringify(lastValue);
}

// export function memoizeOne(resultFn) {
// let lastArgs = [];
// let lastResult;
Expand Down

0 comments on commit 9d7f95d

Please sign in to comment.