简体   繁体   English

Angularjs如何使用ngView处理内存管理?

[英]How does Angularjs handle Memory Management with ngView?

When you are using ngView with say 100 different views each with a different scope. 当您使用ngView时,说100个不同的视图,每个视图具有不同的范围。 Does Angular automatically handle destroying the old templates/scopes or do they stay in memory? Angular会自动处理破坏旧模板/范围还是留在内存中? I'm just curious if Angular handles this by itself before I go and start writing custom code to reduce the memory load. 我很好奇,如果Angular在我开始编写自定义代码以减少内存负载之前自己处理这个问题。 As of right now each new view I go to just stacks up in the memory. 到目前为止,我所看到的每个新视图都会叠加在内存中。

This is an AngularJS specific question. 这是一个AngularJS特定问题。 I know how garbage collection works in javascript. 我知道垃圾收集在javascript中是如何工作的。

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特定问题时,该指令将仅保留当前活动视图的范围 ng-view is one of the scope creating (and scope destroying!) directives. ng-view是范围创建(和范围销毁!)指令之一。 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 . 这可以在AngularJS 源代码中轻松验证。

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 . 路由中引用的所有模板都缓存在$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. 简而言之:无需为ng-view推出自己的范围管理 - 如果您发现任何范围保留,则应将其报告为错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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