0
0
Svelteframework~8 mins

Each blocks ({#each}) in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: Each blocks ({#each})
MEDIUM IMPACT
This affects how many DOM nodes are created and updated during rendering, impacting page load and interaction speed.
Rendering a list of items in Svelte
Svelte
<script>
  import { onMount } from 'svelte';
  let items = [];
  let visibleCount = 20;
  onMount(() => {
    items = Array(1000).fill(0).map((_, i) => i);
  });
</script>

<ul>
  {#each items.slice(0, visibleCount) as item}
    <li>{item}</li>
  {/each}
</ul>
Rendering only a small subset of items reduces DOM nodes and layout cost, improving load and interaction speed.
📈 Performance GainTriggers 20 reflows and paints instead of 1000, reducing blocking time by over 80%.
Rendering a list of items in Svelte
Svelte
<script>
  let items = Array(1000).fill(0).map((_, i) => i);
</script>

<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>
Rendering 1000 items at once creates many DOM nodes and triggers a large layout and paint cost, slowing initial load and interaction.
📉 Performance CostTriggers 1000 reflows and paints on initial render, blocking rendering for 100+ ms on typical devices.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Render all items at once1000 nodes created1000 reflowsHigh paint cost[X] Bad
Render limited items with slice20 nodes created20 reflowsLow paint cost[OK] Good
Rendering Pipeline
The {#each} block creates DOM nodes for each item. The browser must calculate styles, layout, and paint for all these nodes. Large lists increase the cost in Layout and Paint stages.
DOM Construction
Style Calculation
Layout
Paint
⚠️ BottleneckLayout and Paint stages due to many DOM nodes
Core Web Vital Affected
LCP, INP
This affects how many DOM nodes are created and updated during rendering, impacting page load and interaction speed.
Optimization Tips
1Avoid rendering very large lists all at once with {#each}.
2Use slicing or virtualization to limit rendered items.
3Monitor layout and paint costs in DevTools Performance panel.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens if you render a very large list with {#each} without optimization?
AThe page will load instantly with no performance impact.
BThe page may load slowly due to many DOM nodes and layout calculations.
CThe browser will automatically optimize and render only visible items.
DThe list items will not appear on the page.
DevTools: Performance
How to check: Record a performance profile while loading the page with the {#each} block. Look at the Main thread activity and Frames section.
What to look for: Long tasks and many layout and paint events indicate heavy DOM work. Fewer and shorter tasks mean better performance.