# PERF：frontend-store 中似乎存在内存泄漏

**URL:** <https://meta.discourse.org/t/perf-there-seems-to-be-a-memory-leakage-in-frontend-store/393510>\
**Category:** Bug\
**Created:** [2026年一月15日 05:36 UTC](https://meta.discourse.org/t/perf-there-seems-to-be-a-memory-leakage-in-frontend-store/393510 "2026-01-15T05:36:40Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![saquetim](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/saquetim/32/116400_2.png) [@saquetim](https://meta.discourse.org/u/saquetim)\
**Post date:** [2026年一月16日 19:58 UTC](https://meta.discourse.org/t/perf-there-seems-to-be-a-memory-leakage-in-frontend-store/393510/8 "2026-01-16T19:58:49Z")

</div>

> <https://github.com/discourse/discourse/pull/37163>
>
> Fixes a memory leak reported by @small-lovely-cat in https://meta.discourse.org/…t/perf-there-seems-to-be-a-memory-leakage-in-frontend-store/393510/1
> 
> \## Problem
> 
> The store's identity map holds strong references to every model instance ever fetched during a session. These references are never released, causing memory to grow unbounded as users navigate through the application.
> 
> Models for topics, posts, categories, and other resources accumulate indefinitely, even after the user has navigated away and the app no longer needs them.
> 
> \## Why not FIFO/LRU?
> 
> Traditional cache eviction strategies don't work well for an identity map. If we evict an entry while the app still holds a reference to that model (e.g., it's rendered in a component), the object remains in memory anyway. Worse, the next fetch for that ID creates a \*new\* instance—consuming more memory and breaking identity semantics where the same ID should always return the same object.
> 
> \## Solution
> 
> Introduce \`WeakValueMap\`, a Map that holds weak references to its values. When a model instance is no longer referenced anywhere else in the application, it becomes eligible for garbage collection, and the identity map entry is automatically cleaned up.
> 
> \*\*Key implementation details:\*\*
> \- \`WeakRef\` wraps cached values, allowing GC when unreferenced
> \- \`FinalizationRegistry\` removes stale map entries after values are collected
> \- Probabilistic sweep (~1% of \`get()\` calls) as a backup cleanup mechanism
> 
> This makes the identity map self-regulating—it naturally shrinks when models are no longer in use, while still preserving identity semantics for active models.

上面的 PR 将解决 OP 中报告的内存泄漏问题。😃

---

_[View the full topic](https://meta.discourse.org/t/perf-there-seems-to-be-a-memory-leakage-in-frontend-store/393510)._
