Home Angular Tutorials How to Optimize Angular Application with zone.runOutsideAngular() and zone.runTask()

How to Optimize Angular Application with zone.runOutsideAngular() and zone.runTask()

by aouidane.med.amine
264,011 views 5 min read

In this tutorial, we’ll explore some powerful tools to optimize angular application, provided by the library zones.js.

As we all know, Angular is a powerful framework that makes it easy to build complex, dynamic web applications. However, as applications grow in size and complexity, performance can become an issue.
Fortunately, the zone.js library, which is included in Angular by default and used through NgZone service, provides some powerful tools for optimizing the performance of our applications.

In this tutorial, we’ll explore two of these tools: zone.runOutsideAngular() and zone.runTask().

We’ll explain how these methods work, and show you how to use them to optimize angular application.

What is Zone.js ?

zone.js is a JavaScript library that provides a way to intercept and asynchronous operations in the browser. It does this by wrapping asynchronous operations in “zones,” which are essentially execution contexts that can be monitored and controlled.

In an Angular application, zone.js is used to implement the Angular zone, which is responsible for change detection and triggering updates to the user interface.

By intercepting asynchronous operations within the angular zone, zone.js enables Angular to detect changes and update automatically the user interface.

Optimize angular application

Why use zone.runOutsideAngular() ?

When an expensive operation is executed within the Angular zone, it can cause the application to become unresponsive or slow. This is because the operation is executed within the same execution context as change detection, which can cause a “blocking” effect on the user interface.

By using zone.runOutsideAngular() to run expensive operations outside the Angular zone, we can prevent this blocking effect and ensure that our applications remain fast and responsive, that allows us to optimize angular applications easily.

Why use zone.runTask() ?

zone.runTask() can be used to monitor the progress of individual tasks within our applications.

We can use zone.runTask() to monitor the performance of tasks created and run within the Angular zone and find any performance bottlenecks.

This way, even if our apps increase in size and complexity, they will continue to run quickly and responsively since we will have optimized our code for optimal speed. Thus, we optimize angular applications without spending too much time.

 

Using zone.runOutsideAngular()

One common cause of performance issues in Angular applications is running expensive operations within the Angular zone.

The Angular zone is responsible for change detection, which means that any time we modify our application’s state, Angular needs to check to see if anything has changed and update the view accordingly.

If we run expensive operations within the Angular zone, it can cause the application to become unresponsive or slow.

The zone.runOutsideAngular() method provides a way to run expensive operations outside of the Angular zone.

When we use this method, Angular will be aware that changes have occurred, but it won’t perform change detection until the code running outside of the zone has finished executing.

Here’s an example of how to use zone.runOutsideAngular():

				
					import { Component, NgZone } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `Result: {{ result }}`
})
export class MyComponent {
  public result: string;

  constructor(private zone: NgZone) {}

  public ngOnInit(): void {
    this.zone.runOutsideAngular(() => {
      // Perform some expensive computation here...

      this.zone.run(() => {
        this.result = 'Result of computation';
      });
    });
  }
}

				
			

In this example, we’re using zone.runOutsideAngular() to run an expensive computation outside of the Angular zone.

Once the computation is complete, we’re using zone.run() to update the component’s state and trigger change detection.

We can improve the performance of our application and prevent it from becoming unresponsive or slow by using zone.runOutsideAngular() to run expensive operations outside of the Angular zone.

Using zone.runTask()

Another way to optimize angular applications is to use zone.runTask() to track the execution of specific tasks and spot performance bottlenecks.

By creating a new task inside the Angular zone using zone.runTask() method, we could identify and monitor the execution of our code easily.

When the task is finished, we can specify a callback function to run, then we use performance.now() method to calculate the task’s completion time.

This example demonstrate how to use zone.runTask() to measure the performance of an expensive operation:

				
					import { Component, NgZone } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `Result: {{ result }}`
})
export class MyComponent {
  public result: string;

  constructor(private zone: NgZone) {}

  public ngOnInit(): void {
    this.zone.runTask(new Task({
      source: 'MyTask',
      callback: (task) => {
        const startTime = performance.now();

        // Perform some expensive computation here...

        const endTime = performance.now();
        console.log(`Computation took ${endTime - startTime} ms`);

        this.zone.run(() => {
          this.result = 'Result of computation';
        });

        task.invoke();
      },
      onError: (error) => {
        console.error('Error during task execution:', error);
      }
    }));
  }
}

				
			

In this example, we’re creating a new task called “MyTask” using zone.runTask() and running expensive operations inside of it.

As you can see, we’re measuring the time it took for the operation to finish using the “performance.now()” method and logging the results to the console.

Once the operation is complete, we’re using zone.run() to update the component’s state and trigger change detection.

We’re also calling task.invoke() to mark the task as completed and execute any callback functions that were specified.

By using zone.runTask() to track the execution of specific tasks, we can identify performance bottlenecks in our application and optimize our code accordingly.

Conclusion

In this tutorial, we’ve explored two ways to optimize the performance of our Angular applications using the zone.js library.

By using zone.runOutsideAngular() to run expensive operations outside of the Angular zone, we can prevent our applications from becoming unresponsive or slow.

And by using zone.runTask() to track the execution of specific tasks, we can identify performance bottlenecks and optimize our code for maximum performance.

These methods allow us to optimize angular applications by maintaining their performance and speed even if they grow in size and complexity.

References and Links

You may also like