我想先给你一些关于应用程序的描述.之后我会发布一些我可以衡量的记忆统计数据.我使用三种诊断工具来测量已用内存:Windows(7)任务管理器,Firefox关于:内存和Firefox扩展MemChaser.
应用
>应用程序嵌入在页面中,应该加载一次并在那里停留至少24小时
>通过$http()Ajax请求,数据以1到60分钟的间隔连续加载
>数据是具有一些层次结构的JSON对象
>对于此层次结构的每个层,都有一个自定义组件(具有隔离范围)
>数据的选定部分将被注意到并保持在Ajax请求之外
>大多数指令加载一个html文件(通过$http())来编译它作为模板
> Windows任务管理器
The memory used by Firefox increases by 50 – 100 MB per hour.
>关于:记忆
Size (MB) 20 min diff Size (MB) JS-Main-Runtime 32 36/+113% 68 JS-Main-Runtime-GC-Heap-Committed 20 27/+135% 47 Heap-Allocated 54 29/+54% 83 Heap-Committed 63 28/+44% 91 JS-GC-Heap 31 26/+84% 57 Private 156 58/+37% 214 Resident 175 62/+35% 237 VSize 509 86/+17% 595
> MemChaser 0.5.2.1
12:17 12:27 12:57 13:17 Resident (MB) 140 164 243 270 iGC (ms) 42 24 40 42 CC (ms) 3 53 206 286
Resident: Memory used by the process that is present in the physical memory.
iGC: Duration of the last garbage collector activity.
CC: Duration of the last cycle collector activity.
这些结果非常引人注目,似乎循环收集器给出了最好的提示.如果我在没有视图的情况下运行我的应用程序(只是Ajax请求)没有任何戏剧性的事情如果我禁用动态模板加载,则使用动态模板的版本没有明显区别.所以似乎这两个主题不是原因.
我的想法:每个Ajax请求都会创建新的作用域和DOM节点.之后可以建立DOM节点,但是具有数据的范围将可能仍然在存储器中.这可能是我的内存泄漏的原因吗?
那么我应该如何正确使用AngularJS指令,作用域和绑定来避免像这样的内存泄漏?
任何帮助我都会非常高兴.
托比亚斯
从文档:
$destroy()
Removes the current scope (and all of its children) from the parent
scope. Removal implies that calls to $digest() will no longer
propagate to the current scope and its children. Removal also implies
that the current scope is eligible for garbage collection.The $destroy() is usually used by directives such as ngRepeat for
managing the unrolling of the loop. Just before a scope is
destroyed,a $destroy event is broadcasted on this scope.
Application code can register a $destroy event handler that will give
it a chance to perform any necessary cleanup. Note that,in
AngularJS,there is also a $destroy jQuery event,which can be used to
clean up DOM bindings before an element is removed from the DOM.
和
$destroy() must be called on a scope when it is desired for the scope and its child scopes to be permanently detached from the parent and thus stop participating in model change detection and listener notification by invoking.