One of Angular’s most convenient features is two-way data binding. When the model changes value, it is automatically reflected in the UI, and vice versa. For the average web application developer using a framework like Angular for the first time, this seems like pure magic and is a huge time saver.
However, as with most things, the ease of use and convenience comes at a cost. The magic behind Angular’s automatic data binding is powered by watchers. Angular creates a watcher for every model that is bound to UI. During the digest cycle, Angular will go through the list of watchers one by one and check if the value being watched has changed. This is called dirty checking. As the list of watchers grows longer, performance decreases.
The Turn Platform empowers marketers to efficiently manage their campaigns and view important insights. Naturally, as a result, some of our pages are very data intensive, such as our list pages. Our list pages enable users to dive into their campaigns and view performance metrics and metadata. A single list page could have as many as 200 rows and 48 columns, meaning there could be 9,600 cells displaying data and therefore at least 9,600 watchers. We initially implemented the list page purely in Angular, but such a complex data intensive component struggled on initial load and prevented the user from interacting with the page while it rendered the data. As one of the primary components that our users interact with on a daily basis, it was critical that the list pages rendered quickly and responded effortlessly to user interaction. We knew we had to come up with a better solution.
The advantage of this trade-off is that we no longer have to iterate through long lists of watchers to check their state. Instead of dirty checking, React utilizes something called the virtual Document Object Model, or virtual DOM, which is a lightweight in-memory version of the actual DOM. When a component has been updated, React:
- Creates a new virtual DOM.
- Calculates the difference between the newly created virtual DOM and the original virtual DOM.
- Re-renders the parts of the actual DOM that need to be updated using efficient batching and sub-tree rendering operations.
This process is much faster than updating the DOM directly and more importantly, it did not create a watcher for every cell element. React empowered us to have complete control over event listeners. Rather than deciding for us, we could explicitly add them whenever we deemed necessary.
With React and Angular being two of the hottest tools for web applications today, many developers often wonder which one they should use. We say, “Why not both?” Sometimes, you don’t have to choose. Sometimes, you can have your cake and eat it too. Turntable is concrete evidence that you can have best of both worlds.
For more on the Turn Platform, read a post from Apps Engineer Ben Wang on how we're transforming the web user interface.