angularjsperformancedomng-controllerng-app

Angular view performance related to ng-app/ng-controller placement in DOM


I was wondering whether I could gain any significant performance difference in my Angular app (specifically view processing) if I change ng-app and ng-controller attribute placement from i.e. body to some inner-page block element with much smaller DOM subtree?

Suppose I have a very long page with huge amount of content, but only part of it is Angular powered. Everything else is either server generated which means it's somewhat static from the client-side PoV.

Would it be better to put ng-app/ng-controller on only that subnode where Angular actually executes or would it be the same if I put them on body element of this very long page?

Does Angular process the view only of the sub-DOM where ng-app/ng-controller are defined or does it process the whole DOM anyway?

Is there any proof about this or even Angular documentation?


Solution

  • Theoretically/Potentially? Yes, as New Dev mentions, the bootstrap function will have a larger DOM to run compile on, which would take longer than compiling a smaller tree.

    Practically? Probably not. But your best bet is to benchmark your own page.

    As an experiment, you can try the following. I generated a simple random DOM and injected it into a JSFiddle with console.time starting at script load, and ending when the controller is ready. There's a small sub-tree beside (as a sibling) a much larger, 5000-node tree.

    Here's the fiddle wrapping the entire body: http://jsfiddle.net/gruagq8d/

    And here's the fiddle where only the small subset is used: http://jsfiddle.net/h0hod2j8/

    For me, running either of those fiddles repeatedly converges on about 260ms.

    I've also tried running similar code on real webpage sources, such as StackOverflow itself, and found the same results (however I did not publish any of these because publishing other people's real pages to JSFiddle does not feel proper without permission) - you can try this for yourself pretty trivially.

    Admittedly, this doesn't follow great benchmarking methodology, but if wrapping lots of additional DOM nodes caused significant different performance I'd still expect at least some difference in these.

    I don't think that the additional compile time is an issue; for small DOMs it's obviously fast, and for large DOM is very relevant compared to the time it takes your browser to build the DOM in the first place.

    All said, as mentioned before, your best option is to try to run similar benchmarks with your own page.

    EDIT: Modifying the same benchmark to test digest cycles shows that there's no significant difference in those as well:

    Wrapping minimal: http://jsfiddle.net/fsyfn1ee/

    Wrapping whole DOM: http://jsfiddle.net/04tdwxhp/