How does Angularjs handle Memory Management with ngView?


When you are using ngView with say 100 different views each with a different scope. Does Angular automatically handle destroying the old templates/scopes or do they stay in memory? I'm just curious if Angular handles this by itself before I go and start writing custom code to reduce the memory load. As of right now each new view I go to just stacks up in the memory.

This is an AngularJS specific question. I know how garbage collection works in javascript.

Problem courtesy of: mfrancis107


One of the design decisions behind introducing scopes was to ease memory management. By partitioning model's space into sub-parts (scopes) we can remove unneeded parts of the model (scope) and add new when needed. So yes, scopes are important part of the whole memory-management puzzle.

When it comes to your specific question about ng-view - this directive will keep scope only for the currently active view. ng-view is one of the scope creating (and scope destroying!) directives. It will automatically create a new scope when a new view is navigated to and will automatically destroy a scope connected with the old view. This can be easily verified in the AngularJS source code.

The only memory-consuming part to consider are templates fetched over a network. All the templates referenced in a route are cached in the $templateCache. You could evict templates using sparingly if you determine that it tackles a specific perf bottleneck in your app. We just need to realize that it is trading time (network time) for memory consumption.

In short: no need to roll out your own scope-management for the ng-view - if you see any scope retention it should be reported as a bug.

Solution courtesy of: pkozlowski.opensource


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.