From Angular.js to Fine-Grained Reactivity: Part 3 - How to Optimize the Render Phase
In the last article of this series, we saw how to use the Proxy API to notify changes to the templates. For example, this controller: // simple-controller.js export function SimpleController ( $scope ) { $scope . name = " Mario " ; } produces a change like this: let changes = { name : " Mario " , }; update ( changes ); Suppose now that we have a controller with multiple assignments: //…
This is the third part of a series exploring optimization techniques for rendering phases in Angular.js and Reactivity. The previous article introduced using the Proxy API to notify templates of changes. In this article, we address the rendering performance issue caused by multiple updates triggered by individual assignments within a controller.
Consider a controller with multiple assignments, such as:
$scope.name = 'Mario';
$scope.age = 24;
Each assignment generates a new change, resulting in multiple update calls. In larger applications, this can lead to dozens of controller executions with numerous assignments, and multiple assignments to the same property, potentially causing flickering effects on the rendered view.
The solution is to queue mutations via microtasks in the event loop, ensuring changes are merged before calling the update function. Microtasks run after the calling function returns but before the next tick of the event loop checks its macrotask queue. This occurs prior to updating the view with new values.
To implement this solution, we create a batching engine that merges changes and schedules updates using a microtask. Pending changes are stored in the pendingChanges object, which is updated using Object.assign to overwrite previous values for the same key. A flag (isScheduled) prevents multiple redundant microtasks from being enqueued.
The proxies must now call the scheduleUpdate method instead of the update function directly when intercepting set operations. This batching engine effectively addresses the problem of multiple mutations within the same controller execution, optimizing the rendering phase and improving user experience.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.