Using the `immutable` Compiler Option

<svelte:options immutable> is a performance optimization you can add to your Svelte components. There is no difference in compiled output size, but re-rendering mutable variables will be faster.

The official docs are here and official example is here. The example demonstrates a compelling case to use the immutable flag when possible, because it significantly optimizes child components in a list. This is likely one of the most common performance gotchas.

The parent component can opt into mutability, and use mutable data structures like maps, without de-optimizing all of its children.

  • Objects, arrays, and functions are mutable variables in JavaScript.
  • Mutations in Svelte are compiled to an $$invalidate function in the compiled output.
  • The default option, immutable: false, will always treat calls to $$invalidate with mutable variables to always be true. In other words, it will always rerender, to ensure correctness in case the variable was modified.
  • Setting immutable to true opts out of this and relies on simple equality: a !== b.

You can see the difference between safe_not_equal and not_equal in the source code here. This is the only place in Svelte affected by the immutable compiler option.

Published:
Last update: