
Memory Leak Audit
OfficialFreePrevent memory leaks with effective coding patterns.
Free · Opens the source repo
What Memory Leak Audit does
Memory leaks are a common issue in software development, particularly in environments like VS Code where event listeners and DOM handlers are frequently used. The Memory Leak Audit skill provides developers with a structured approach to identify and fix memory leaks in their code. By following the outlined patterns and best practices, users can ensure that their applications manage resources efficiently, preventing unnecessary memory consumption and potential performance degradation.
This skill is particularly useful when reviewing code that registers event listeners or handles DOM events. It guides users through a checklist of best practices, such as using addDisposableListener instead of raw event handlers, and employing Event.once for one-time events. The skill also addresses common pitfalls, like registering listeners in methods called repeatedly, which can lead to multiple listeners being added unnecessarily, causing memory bloat.
In addition to providing guidelines, the skill includes practical code examples that illustrate both correct and incorrect implementations. This hands-on approach helps developers quickly grasp the importance of proper resource management. The audit checklist covers various scenarios, including lifecycle events and resource pooling, ensuring that users are equipped to handle a wide range of coding situations.
Ultimately, the Memory Leak Audit skill is designed for developers who want to enhance their coding practices and maintain the performance of their applications. By integrating these patterns into their workflow, they can significantly reduce the risk of memory leaks and improve the overall stability of their codebase.
When to use it
Use this skill when reviewing code that involves event listeners, DOM handlers, or when addressing reported memory leaks.
When not to use it
This skill is not suitable for scenarios where memory management is not a concern or for simple scripts that do not involve complex event handling.
What you can build with it
Reviewing Event Listeners
When auditing code that registers multiple event listeners, use this skill to identify and replace raw event handlers with `addDisposableListener`.
Fixing Memory Leak Reports
If you receive reports of increasing listener counts, apply the skill's patterns to locate and fix the source of the leaks.
Managing Repeated Method Calls
When creating objects in frequently called methods, use `MutableDisposable` to ensure that listeners are not registered multiple times.
How to install Memory Leak Audit
View source1. Install with the skills CLI
npx skills add microsoft/vscode/memory-leak-audit --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by microsoftMemory Leak Audit
The #1 bug category in VS Code. This skill encodes the patterns that prevent and fix leaks.
When to Use
- Reviewing code that registers event listeners or DOM handlers
- Fixing reported memory leaks (listener counts growing over time)
- Creating objects in methods that are called repeatedly
- Working with model lifecycle events (onWillDispose, onDidClose)
- Adding event subscriptions in constructors or setup methods
Audit Checklist
Work through each check in order. A single missed pattern can cause thousands of leaked objects.
Step 1: DOM Event Listeners
Rule: Never use raw .onload, .onclick, or addEventListener() directly. Always use addDisposableListener().
// BAD — leaks a listener every call
this.iconElement.onload = () => { ... };
// GOOD — tracked and disposable
this._register(addDisposableListener(this.iconElement, 'load', () => { ... }));
Validated by: PR #280566 — Extension icon widget leaked 185 listeners after 37 toggles.
Step 2: One-Time Events
Rule: Use Event.once() for events that should only fire once (lifecycle events, close events, first-change events).
// BAD — listener stays registered forever after first fire
model.onDidDispose(() => store.dispose());
// GOOD — auto-removes after first invocation
Event.once(model.onDidDispose)(() => store.dispose());
Validated by: PRs #285657, #285661 — Terminal lifecycle hacks replaced with Event.once().
Step 3: Repeated Method Calls
Rule: Objects created in methods called multiple times must NOT be registered to the class this._register(). Use MutableDisposable or return IDisposable to the caller.
// BAD — every call adds another listener to the class store
startSearch() {
this._register(this.model.onResults(() => { ... }));
}
// GOOD — MutableDisposable ensures max 1 listener
private readonly _searchListener = this._register(new MutableDisposable());
startSearch() {
this._searchListener.value = this.model.onResults(() => { ... });
}
When the event should only fire once per method call, combine Event.once() with MutableDisposable — this auto-removes the listener after the first invocation while still guarding against repeated calls:
private readonly _searchListener = this._register(new MutableDisposable());
startSearch() {
this._searchListener.value = Event.once(this.model.onResults)(() => { ... });
}
Validated by: PR #283466 — Terminal find widget leaked 1 listener per search.
Step 4: Model-Tied DisposableStores
Rule: When creating a DisposableStore tied to a model's lifetime, register model.onWillDispose(() => store.dispose()) to the store itself.
const store = new DisposableStore();
store.add(model.onWillDispose(() => store.dispose()));
store.add(model.onDidChange(() => { ... }));
Validated by: Pattern used in chatEditingSession.ts, fileBasedRecommendations.ts, testingContentProvider.ts.
Step 5: Resource Pool Patterns
Rule: When using factory methods that create pooled objects (lists, trees), disposables must be registered to the individual item, not the pool class.
// BAD — registers to pool, never cleaned per item
createItem() {
const item = new Item();
this._register(item.onEvent(() => { ... }));
return item;
}
// GOOD — wrap with item-scoped disposal
createItem(): IDisposable & Item {
const store = new DisposableStore();
const item = new Item();
store.add(item.onEvent(() => { ... }));
return { ...item, dispose: () => store.dispose() };
}
Validated by: PR #290505 — Chat content parts CollapsibleListPool and TreePool leaked disposables.
Step 6: Test Validation
Rule: Every test suite that creates disposable objects must call ensureNoDisposablesAreLeakedInTestSuite().
import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js';
suite('MyFeature', () => {
ensureNoDisposablesAreLeakedInTestSuite();
test('does something', () => {
// test disposables are tracked automatically
});
});
Quick Reference
| Scenario | Pattern | Anti-Pattern |
|---|---|---|
| DOM events | addDisposableListener() | .onclick =, addEventListener() |
| One-time events | Event.once(event)(handler) | event(handler) for lifecycle |
| Repeated methods | MutableDisposable or return IDisposable | this._register() in non-constructor |
| Model lifecycle | store.add(model.onWillDispose(...)) | Forgetting cleanup |
| Pooled objects | Item-scoped DisposableStore | Pool-scoped this._register() |
| Tests | ensureNoDisposablesAreLeakedInTestSuite() | No leak checking |
Verification
After fixing leaks, verify by:
- Checking listener counts before/after repeated operations
- Running
ensureNoDisposablesAreLeakedInTestSuite()in tests - Confirming object counts stabilize (don't grow linearly with usage)
- For chat-specific leaks: Run the chat memory leak checker via
npm run perf:chat-leak(see thechat-perfskill). It sends N messages in a single session, forces GC between each, and uses linear regression on heap/DOM samples to detect per-message growth. A slope above 2 MB/msg indicates a leak. Use--messages 20 --verbosefor more accurate results.
Frequently asked questions about Memory Leak Audit
Similar skills
Heap Snapshot Analysis
Investigate V8 heap snapshots for memory issues.
VS Code Performance Workflow
Automate performance investigations in VS Code.
CPU Profile Analysis
Analyze V8 and Chrome performance profiles for optimization.
Chat Performance Testing
Benchmark and validate chat UI performance in VS Code.
Vercel React Best Practices
Optimize your React and Next.js applications for performance.
Claude Monitor
Diagnose performance issues with Claude Code and local systems.
