Understanding Incremental DOM and Virtual DOM
Understanding Incremental DOM and Virtual DOM
12 October 2020
What is Virtual DOM? How does it Work?
Virtual DOM was first used by React, which is defined by this key idea:
Each component creates a new virtual DOM tree every time it gets rerendered. React compares the new virtual DOM tree with the old one and then applies a series of changes to the browser DOM to match the new virtual DOM tree.
Advantages of Virtual DOM
- We can use any programming language to execute the component’s render function, so we don’t need to compile anything. React developers mainly use JSX, but we can use plain JavaScript as well.
- We get value as a result of the rendering component. It can also be used for testing and debugging purposes.
Incremental DOM
Incremental DOM is used internally at Google, and is defined by this key idea:
Each component gets compiled into a series of instructions. These instructions then create DOM trees and update them in-place when the data changes.
The template function holds the instructions for rendering and updating the DOM. Note that the instructions are not interpreted by the framework’s rendering engine. They are the rendering engine.
Why Incremental DOM?
Why did the Google team prefer incremental DOM instead of virtual DOM?
The goal was to make applications perform well on mobile devices. This essentially meant optimizing two things: the bundle size and the memory footprint.
To achieve these two goals:
- The rendering engine itself needed to be tree shakable
- The rendering engine should have a low memory footprint
Why is Incremental DOM Tree Shakable?
When practicing incremental DOM, the framework does not interpret the component. Rather, the component references instructions. If it doesn’t reference a particular instruction, it will then never be used. And since we know this at compile-time, we can eliminate the unused instruction from the bundle.
Virtual DOM requires an interpreter. What a part of that interpreter is required and what part isn’t isn’t known at compile time, so we’ve to ship the entire thing to the browser.
Why does an Incremental DOM have a Low Memory Footprint?
Virtual DOM generates a whole tree from scratch every time you rerender.
On the other hand, Incremental DOM doesn’t require any memory to re-render the view if it doesn’t change the DOM. We only need to allocate the memory when the DOM nodes are added or removed. And the size of the allocation is equivalent to the size of the DOM change.
Since most of the render/template calls don’t change anything (or change very little), this can result in huge memory savings.
Ivy and Incremental DOM?
Angular has always been focusing on HTML and templates. This is why the main advantage of using virtual DOM could never apply to Angular.
Given this, and the tree shakability and memory footprint of the incremental DOM, I think it was the right choice to use incremental DOM as the base of the new rendering engine.