Search code examples
foreachsveltesveltekit

How does Svelte Kit benefit from specifying unique IDs for looped items, and what are the performance implications of not doing so?


User The problem at hand revolves around understanding the necessity of specifying unique IDs for looped items in Svelte Kit. Specifically, the inquiry delves into the reasons behind this requirement, the performance implications of not adhering to it, and how Svelte Kit optimizes rendering processes when unique IDs are provided. If you give any example that to like a bench marks It would really help me..! :)

Example with Unique IDs

<script>
    let people = [
        { name: 'yoshi', beltColour: 'black', age: 25, id: 1 },
        { name: 'mario', beltColour: 'orange', age: 45, id: 2 },
        { name: 'luigi', beltColour: 'brown', age: 35, id: 3 }
    ];
</script>

<h1>Loops</h1>

{#each people as p (p.id)}
    <h3>{p.name}</h3>
    <p>beltColour: {p.beltColour}</p>
    <p>age: {p.age}</p>
{/each}

Example without Unique IDs

<script>
    let people = [
        { name: 'yoshi', beltColour: 'black', age: 25 },
        { name: 'mario', beltColour: 'orange', age: 45 },
        { name: 'luigi', beltColour: 'brown', age: 35 }
    ];
</script>

<h1>Loops</h1>

{#each people as p}
    <h3>{p.name}</h3>
    <p>beltColour: {p.beltColour}</p>
    <p>age: {p.age}</p>
{/each}

The first example includes unique IDs for each item in the loop, while the second example does not. Observing the difference in performance between the two scenarios, especially with a large dataset, can help understand the significance of providing unique IDs in Svelte Kit applications.

I needed a proper benchmark example if possible :)


Solution

  • This does not really have anything to do with SvelteKit, this is a core Svelte mechanism.

    It also has no effect unless you update the list later.

    If a key exists, Svelte can move existing DOM nodes and do less work, causing fewer DOM updates. Not providing a key can also cause bugs if there is local state, e.g. when rendering components in a loop which declare their own variables.

    Example: You do not have a key and insert a new item at the front:

    people = [{ name: 'wario', beltColour: 'yellow', age: 42 }, ...people];
    

    Svelte has no idea what operation happened here, it just notices that the list changed and is longer now. It (roughly) will do the following:

    • Add new h3, p, p at the end, inserting the values of the item at that index (Luigi).
    • Update every other DOM element changing the contents.
      The DOM elements that contained Yoshi's data are changed to those of Wario, those of Mario are changed to Yoshi's, etc.

    REPL showing this

    If there is a key, the existing elements are left alone. The values might be diffed but since the other items did not change nothing happens in the DOM.

    Move operations and deletions also have a minimal impact this way.

    REPL using a key