From c70a4c5bb86e67dce931b60a0347a52561b31ba0 Mon Sep 17 00:00:00 2001 From: Lenz Weber-Tronic Date: Fri, 19 Apr 2024 11:28:07 +0200 Subject: [PATCH] AutoCleanedCache: only schedule batched cache cleanup if the cache is full Fixes #11790 This prevents timeouts from being set when they are not necessary. --- .changeset/cuddly-emus-fail.md | 5 +++++ src/utilities/caching/caches.ts | 27 ++++++++++++++++++--------- 2 files changed, 23 insertions(+), 9 deletions(-) create mode 100644 .changeset/cuddly-emus-fail.md diff --git a/.changeset/cuddly-emus-fail.md b/.changeset/cuddly-emus-fail.md new file mode 100644 index 00000000000..d3830efd702 --- /dev/null +++ b/.changeset/cuddly-emus-fail.md @@ -0,0 +1,5 @@ +--- +"@apollo/client": patch +--- + +AutoCleanedCache: only schedule batched cache cleanup if the cache is full (fixes #11790) diff --git a/src/utilities/caching/caches.ts b/src/utilities/caching/caches.ts index 6acbdb88d34..a42cd24a06d 100644 --- a/src/utilities/caching/caches.ts +++ b/src/utilities/caching/caches.ts @@ -1,8 +1,15 @@ -import type { CommonCache } from "@wry/caches"; import { WeakCache, StrongCache } from "@wry/caches"; -const scheduledCleanup = new WeakSet>(); -function schedule(cache: CommonCache) { +interface CleanableCache { + size: number; + max?: number; + clean: () => void; +} +const scheduledCleanup = new WeakSet(); +function schedule(cache: CleanableCache) { + if (cache.size <= (cache.max || -1)) { + return; + } if (!scheduledCleanup.has(cache)) { scheduledCleanup.add(cache); setTimeout(() => { @@ -14,7 +21,7 @@ function schedule(cache: CommonCache) { /** * @internal * A version of WeakCache that will auto-schedule a cleanup of the cache when - * a new item is added. + * a new item is added and the cache reached maximum size. * Throttled to once per 100ms. * * @privateRemarks @@ -35,8 +42,9 @@ export const AutoCleanedWeakCache = function ( */ const cache = new WeakCache(max, dispose); cache.set = function (key: any, value: any) { - schedule(this); - return WeakCache.prototype.set.call(this, key, value); + const ret = WeakCache.prototype.set.call(this, key, value); + schedule(this as any as CleanableCache); + return ret; }; return cache; } as any as typeof WeakCache; @@ -48,7 +56,7 @@ export type AutoCleanedWeakCache = WeakCache; /** * @internal * A version of StrongCache that will auto-schedule a cleanup of the cache when - * a new item is added. + * a new item is added and the cache reached maximum size. * Throttled to once per 100ms. * * @privateRemarks @@ -69,8 +77,9 @@ export const AutoCleanedStrongCache = function ( */ const cache = new StrongCache(max, dispose); cache.set = function (key: any, value: any) { - schedule(this); - return StrongCache.prototype.set.call(this, key, value); + const ret = StrongCache.prototype.set.call(this, key, value); + schedule(this as any as CleanableCache); + return ret; }; return cache; } as any as typeof StrongCache;