Reactgular
Reactgular

Reputation: 54811

Am I saving myself anything by checking for Zone?

I have a global function that lets me run a function inside an Angular zone when I don't know if that part of the code was run from outside of Angular.

Here's the function:

export class Zones {
    public static maybe(zone: NgZone, callee: () => any) {
        return NgZone.isInAngularZone()
            ? callee()
            : zone.run(callee);
    }
}

After I started using this function. I started to wonder if this check was redundant. Maybe the NgZone.run() method already calls isInAngularZone and does the above logic also.

I tried looking at the Angular source code, but zones are handled by another library and I got lost trying to follow the execution path.

Here's the zone project:

https://github.com/angular/zone.js/

So I continue to use the above function but want to verify that it's needed.

Upvotes: 2

Views: 1586

Answers (1)

Mike Hill
Mike Hill

Reputation: 3782

NgZone.run() is just a delegate to Zone.prototype.run() for the angular zone and does not prevent additional frames. Rather, it tracks the nesting depth of the current angular zone so that it can defer zone turn operations (e.g., change detection) until after all frames within the angular zone have completed. Because of this, your guard would provide a small performance boost in certain cases. Keep in mind that the cost of adding an additional zone frame should be very small, though, so this would likely be most useful for functions that get called very frequently.

The NgZone source can be found here: https://github.com/angular/angular/blob/bebedfed24d6fbfa492e97f071e1d1b41e411280/packages/core/src/zone/ng_zone.ts#L233

The invocation of a task on NgZone.inner (the angular zone) triggers the onEnter() and onLeave() functions, which manage the nesting level and trigger angular zone turn events when necessary.

And the ApplicationRef_ source, which is where many (all?) of Angular's primary hooks into zone turns are applied, can be found here: https://github.com/angular/angular/blob/c59c390cdcd825cca67a422bc8738f7cd9ad42c5/packages/core/src/application_ref.ts#L443

The key statement for change detection is this.tick(). The ApplicationRef.tick() function is what triggers the change detection cycle.

Upvotes: 2

Related Questions