bcquality/microsoft/knowledge/performance/avoid-growing-globals-in-singleinstance-subscribers.md
Jesper Schulz-Wedde 292bdabe27
Promote performance knowledge from community to Microsoft layer (#50)
Pure git-mv relocation of all 7 performance articles from community/knowledge/performance/ to microsoft/knowledge/performance/. No content changes.

Co-authored-by: Jesper Schulz-Wedde <jesper.schulzwedde@microsoft.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-07-01 10:41:01 +02:00

28 lines
1.6 KiB
Markdown

---
bc-version: [all]
domain: performance
keywords: [singleinstance, subscriber, event, memory, session]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Avoid growing globals in SingleInstance subscribers
> Contributions welcome — open a PR to refine or extend this article.
## Description
A codeunit with `SingleInstance = true` is allocated once per session and lives until the session ends. Global variables on it are never collected between event fires. A subscriber that accumulates data into a global — buffering payloads, appending to a list, caching without a cap — steadily grows its session footprint for the entire user session. The symptom is memory that only recovers on sign-out, and it surfaces only on long-running sessions.
## Best Practice
Keep the global footprint on a SingleInstance subscriber bounded and intentional: a handful of flags, a setup record, a bounded cache with a maximum size. When cross-event state is genuinely needed, define an explicit reset point — end of a business process, arrival of a specific terminal event — that clears the growing collection.
See sample: `avoid-growing-globals-in-singleinstance-subscribers.good.al`.
## Anti Pattern
A SingleInstance subscriber that appends each event's payload to a global list, dictionary, or temporary record without a cap or cleanup trigger. The list grows for hours, memory pressure builds quietly, and debugging the root cause on a live environment is substantially harder than noticing the unbounded append in code review.
See sample: `avoid-growing-globals-in-singleinstance-subscribers.bad.al`.