I use Angular for my day job and am learning Svelte on the side. I understand that neither Angular or Svelte use a virtual dom and diffing. I understand that both have other change detection mechanisms, and, from what I've researched, they look similar. Can someone explain to me how each method is unique and how Angular and Svelte's change detection mechanisms differ?
1 Answer
Disclaimer: I don't know the inner workings of neither Angular nor Svelte very deeply, so take my answer with a grain of salt.
Change detection in Angular is done by some form of dirty-checking. A check is run each time Angular is told to do so. In normal Angular projects that's achieved by using Zone.js
which patches all possible sources of events, for example setInterval
or DOM event listeners. When a patched event fires, Angular triggers the change detection. Then each variable that Angular is interested in is compared with the previous state, and if they are different, stuff is rerendered. This blog post explains the concept in more detail.
Svelte does not do dirty-checking, instead it analyses at compile-time each variable that could trigger a repaint and wraps the assignments with $$invalidate
calls. So foo = 'bar'
becomes $$invalidate(.., foo = "bar");
(side node: this is why things like array.push(item)
do not trigger - there is no assignment -, a common confusion for new Svelte developers). All places where variables were invalidated will be repainted in the next browser tick.