Skip to content

Commit

Permalink
perf(store): improve compliant prop getter
Browse files Browse the repository at this point in the history
This commit enhances the `compliantPropGetter` function's implementation. The prop getter
is heavily utilized in NGXS. I noticed that the function unnecessarily copies `paths`. It
now returns a function that accepts an object as a parameter and attempts to select a property
deeply. We've replaced the use of `reduce` with a single for-loop, making it simpler. Though
it doesn't significantly impact size, there's only a minor difference in production bundle size.

Regarding performance, I checked the `perf.link` service and got the following results:
- Old compliant prop getter: 220,410 ops/s
- New compliant prop getter: 360,480 ops/s

I generated a deeply nested object and set my CPU slowdown to 6x. The new implementation is only
30% faster, but it's reasonable to have a slightly faster implementation if possible. At least it's
not causing any negative impact.
  • Loading branch information
arturovt committed Mar 12, 2024
1 parent 81baa9d commit c700dfa
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/store/src/internal/internals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,13 @@ export interface StatesAndDefaults {
* @ignore
*/
function compliantPropGetter(paths: string[]): (x: any) => any {
const copyOfPaths = paths.slice();
return obj => copyOfPaths.reduce((acc: any, part: string) => acc && acc[part], obj);
return obj => {
for (let i = 0; i < paths.length; i++) {
if (!obj) return undefined;
obj = obj[paths[i]];
}
return obj;
};
}

/**
Expand Down

0 comments on commit c700dfa

Please sign in to comment.