Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Angularjs handle Memory Management with ngView?

Tags:

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.

like image 202
mfrancis107 Avatar asked Jun 05 '13 19:06

mfrancis107


1 Answers

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.

like image 110
pkozlowski.opensource Avatar answered Sep 22 '22 13:09

pkozlowski.opensource