Skip to content

Fixing memory leak when removing tracks / streams#6

Merged
moufmouf merged 2 commits intomasterfrom
weak-sendermap
Dec 20, 2025
Merged

Fixing memory leak when removing tracks / streams#6
moufmouf merged 2 commits intomasterfrom
weak-sendermap

Conversation

@moufmouf
Copy link
Collaborator

The _senderMap keeps references to no more used MediaStream / MediaTracks.
In an application where many tracks will be added/removed from a remote peer,
the "dead" tracks keep accumulating in _senderMap.

To avoid this, we turn _senderMap and its inner map into WeakMap.
This way, if the track is never used anymore, it will be freed from memory.

The _senderMap keeps references to no more used MediaStream / MediaTracks.
In an application where many tracks will be added/removed from a remote peer,
the "dead" tracks keep accumulating in _senderMap.

To avoid this, we turn _senderMap and its inner map into WeakMap.
This way, if the track is never used anymore, it will be freed from memory.
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses a memory leak in the simple-peer library by converting the _senderMap data structure from regular Map objects to WeakMap objects. In applications where many tracks are frequently added and removed from remote peers, the previous implementation would retain references to unused MediaStream and MediaStreamTrack objects, preventing garbage collection.

Key Changes

  • Changed _senderMap from Map to WeakMap for both the outer map (track → submap) and inner maps (stream → sender)
  • This allows tracks and streams to be garbage collected when no longer referenced by the application, while maintaining functional correctness

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@moufmouf moufmouf merged commit 697fdb8 into master Dec 20, 2025
1 check passed
@moufmouf moufmouf deleted the weak-sendermap branch December 20, 2025 16:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant