Skip to content

Commit

Permalink
Perf: improve useMemoized callback execution time (#5190)
Browse files Browse the repository at this point in the history
* Perf: improve useMemoized execution time

* Changelog

* Check cache before next cache

* Use single lookup but add to both arrays

* Address comments
  • Loading branch information
OEvgeny committed May 17, 2024
1 parent aaff0e6 commit 6eb0f92
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Notes: web developers are advised to use [`~` (tilde range)](https://github.com/
- Fixes [#5175](https://github.com/microsoft/BotFramework-WebChat/issues/5175). `PrecompiledGlobalize.js` is emitted instead of `.cjs`, by [@compulim](https://github.com/compulim) in PR [#5181](https://github.com/microsoft/BotFramework-WebChat/pull/5181)
- Improved performance for `BasicTranscript`, in PR [5183](https://github.com/microsoft/BotFramework-WebChat/pull/5183), by [@OEvgeny](https://github.com/OEvgeny)
- Fixed potential memory usage issues caused by `useActivitiesWithRenderer`, in PR [5183](https://github.com/microsoft/BotFramework-WebChat/pull/5183), by [@OEvgeny](https://github.com/OEvgeny)
- Improved performance for `useMemoized`, in PR [5190](https://github.com/microsoft/BotFramework-WebChat/pull/5190), by [@OEvgeny](https://github.com/OEvgeny)

### Changed

Expand Down
29 changes: 21 additions & 8 deletions packages/component/src/hooks/internal/useMemoized.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,30 @@ export default function useMemoized<TFinal, TArgs>(fn: Fn<TArgs, TFinal>, deps:
nextCacheRef.current = [];

const memoizedFn = (...args) => {
const { current: fn } = fnRef;
const { current: cache } = cacheRef;
const { current: nextCache } = nextCacheRef;
const { result } = [...cache, ...nextCache].find(
const fn = fnRef.current;
const cache = cacheRef.current;
const nextCache = nextCacheRef.current;

const cached = cache.find(
({ args: cachedArgs }) =>
args.length === cachedArgs.length && args.every((arg, index) => Object.is(arg, cachedArgs[+index]))
) || { result: fn(...args) };
// index is guarented to be a number here
// eslint-disable-next-line security/detect-object-injection
args.length === cachedArgs.length && args.every((arg, index) => Object.is(arg, cachedArgs[index]))
);
if (cached) {
cached.args = args;
nextCache.push(cached);
return cached.result;
}

nextCache.push({ args, result });
const nextCached = {
args,
result: fn(...args)
};
nextCache.push(nextCached);
cache.push(nextCached);

return result;
return nextCached.result;
};

return memoizedFn;
Expand Down

0 comments on commit 6eb0f92

Please sign in to comment.