I'm encountering many memory leaks when using both Svelte 4 and 5 on reasonably complex projects, and having trouble identifying what I'm doing wrong.
Here is an extremely simplified Svelte 5 example (adapted from svelte-7GUIs) that seems to present a memory leak.
<script lang="ts"> class Circle { cx: number; cy: number; constructor(clientX: number, clientY: number) { this.cx = +clientX.toFixed(); this.cy = +clientY.toFixed(); } } let circles = $state<Circle[]>([]); function addCircles() { for (let i = 0; i < 2; i++) { circles.push(new Circle(Math.random() * 600, Math.random() * 400)); } } function deleteCircle() { circles.shift(); }</script><div class="space-y"><div class="actions flex-center"><button onclick={addCircles}>Add 2 Circles</button><button onclick={deleteCircle}>Delete Circle</button></div><svg viewBox="0 0 600 400"> {#each circles as circle}<circle {...circle} r={40} fill="#444"></circle> {/each}</svg></div>Running the above, I press "Add 2 Circles" once and "Delete Circle" twice. The canvas is clear, but inspecting the heap using Chrome dev tools and I can see that an instance of the Circle class remains.
Repeating the process, these lost instances of Circle continue to accumulate.
In this particular example, if I switch circles.shift() to instead use pop or slice, then the memory leak seems to disappear.
For more complex examples, I've also seen similar issues when using SvelteMap instead of $state([]).
Can anyone explain why this is happening?
