简体   繁体   中英

Angular2: How are change detection triggered?

I am currently trying to debug my application performance. It turns out that many frames take more than 200ms, and most of the time is spent in NumberFormat.format(), due to the various number pipes used. In the developers tools timeline, I see that change detection is triggered more often than required.

For a single XHR ready state change of a single request, Lifecycle.tick() is called 11 times. I expected this to happen only once I assign the final result to a local field used in the template. Even though the template bindings are not modified, running NumberFormat.format() on each records 11 times in a frame causes a noticable lag in the app.

This is the Promise chain used in my code once the XHR ready state changes, in this case a search request:

  • The Promise wrapping the request resolves the response
  • An array is constructed by parsing the response JSON
  • For each item in the array, a local model (ItemModel) is constructed:
    • For each reference to other entities, the entity is fetched from the cache or, if absent, from the remote server; then converted to a local model instance. Once all references are fetched, the Promise resolves the ItemModel instance. Note that this may cause several new Promise to be created, as several levels of references need to be resolved. Usually, entities are in the cache and these Promises resolve directly.
  • The result, an array of ItemModel, is assigned to a field in the controller.

This sequence runs pretty fast. However, as seen in the timeline, Lifecycle.tick() is called each time after a local model instance is created. So if 10 references need to be resolved to build the complete local model tree, Lifecycle.tick() will be called 10 times. Why?

It also seems that sometimes Zone.fork is called when I create a local model. Why and why not always?

I'd be happy to hear more on how zones and change detection are triggered in order to improve my app performances.

Developer tools profile, timeline and network samples can be found here (expire on Oct 11 2015) Application code can be found here .

I finally got around this by using immutables collections from immutable-js and changing the changeDetection strategy to ChangeDetectionStrategy.OnPush .

For informations about change detection in angular2: http://victorsavkin.com/post/114168430846/two-phases-of-angular-2-applications

This blog contains other useful resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM