Skip to content

{#each} causes memory leak for quickly changing cyclic buffers (stream chat) #14497

@rwmb

Description

@rwmb

Describe the bug

Using each with an array of limited size that quickly changes its elements (cyclic buffer) causes a memory leak with thousands of detached elements (1 per array item deleted).

Reproduction

I'm creating a chat application with Svelte.

I'm using the logic below with an array that has data pushed and shifted everytime a viewer sends a message. It was going well performance-wise until I started adding badges.

My biggest problem rn is that I'm getting detached elements for images and other components that use the array variables (like user badges, etc). I'm not great at debugging front-end, so I don't know where to start. There is so much memory leak that the tab process hits 1gb in a few minutes.

--- +page.svelte    
WebClientSocket.getInstance().onEvent('message', (message: SocketEvent<EventPayload>) => {
  chat.push(message);
  if (chat.length > 10) {
    chat.shift();
  }
});

...

{#each chat as message}
  <ChatElement element={message} />
{/each}

--- ChatElement.svelte
{#if element.type === EventType.CHAT_MESSAGE}
    <ChatMessage entry={element as SocketEvent<MessageEventPayload>} />
{/if}

--- ChatMessage.svelte
<p class={"message-grid " + theme}>
  <span class="user-info">
    <PlatformIcon platform={entry.platform} />
    <span class="username">{entry.payload.user.name}</span>
    {#each entry.payload.user.badges || [] as badge}
      <Badge {badge} />
    {/each}
  </span>
  <span class="message-container">
    {entry.payload.message.text}
    <MessageElement message="{entry.payload.message}"/>
  </span>
</p>

--- Badge.svelte
{#if typeof badge === 'string'}
  <img src={badge} alt=":p" />
{:else}

(thousands of detached elements)
image

Logs

No response

System Info

System:
    OS: Windows 10 10.0.19045
    CPU: (12) x64 Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz
    Memory: 45.00 GB / 63.94 GB
  Binaries:
    Node: 23.1.0 - C:\Program Files\nodejs\node.EXE
    npm: 10.9.0 - C:\Program Files\nodejs\npm.CMD
    bun: 1.1.35 - ~\.bun\bin\bun.EXE
  Browsers:
    Edge: Chromium (127.0.2651.74)
    Internet Explorer: 11.0.19041.4355
  npmPackages:
    svelte: ^5.0.0 => 5.2.12

Severity

blocking all usage of svelte

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions