How to turn on Angular Debug Tools to measure change detection cycle time
--
Angular has a tool that helps developers to measure how long will it take for a change detection cycle on average for a specific screen in your Angular application, but it is turned off by default.
Turn on Angular Debug Tools
To turn this feature on, just make a small change in your main.ts file as below
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then((module) => {
const appRef = module.injector.get(ApplicationRef);
const appComponent = appRef.components[0];
enableDebugTools(appComponent);
})
.catch((err) => console.error(err));
The above code will get a reference to the application and calling enableDebugTools
with one parameter is the appRef
.
Run change detection and measure the average time
To measure the change detection cycle, in your application, go to the screen that you would like to check, then open the Chrome Dev Tool by pressing Ctrl + Shift + I, then open the Console tab.
In the console tab, enter this command
ng.profiler.timeChangeDetection();
After a few moments, you will see the information logged in the console like this
ng.profiler.timeChangeDetection();
ran 884 change detection cycles
0.57 ms per check
Behind the scene, Angular will run several change detection cycles without any user interaction and the time per check is the average number of these change detection cycles.
As a best practice, this average number should be lower than 3 milliseconds.
View result in more details
In case the number is grater than 3 milliseconds, you can run this command to see the details information.
ng.profiler.timeChangeDetection({ record: true });
After running this command, in your Chrome Dev Tool, go to the JavaScript Profiler tab, and you will see a profile named Change Detection in the left panel, click on this link and you will see more details here.
If you can not see the JavaScript Profiler in your dev Tool, simply click on the three dot button in the top right corner of Dev Tools window, select More tools, then select JavaScript Profiler.
Thanks for reading and happy coding!