Memory leak in Ionic(or angular)?

前提是你 提交于 2019-12-08 03:54:39

If you follow the chart, you can see that the issue is the number of Event Listeners that are issued. Due to the way that $watch works within angular, removing an element from an array and then adding a new element doesn't remove the $watch on the old element, causing the number of Event listeners to continue to spawn infinitely.

By default, the $watch() function only checks object reference equality. This means that within each $digest, angular will check to see if the new and old values are the same "physical" object. This means that the vanilla $watch() statement will only invoke its handler if you actually change the underlying object reference.

There are two ways to solve this issue. Firstly, you can use the new Bind Once syntax that is provided in Angular 1.3. Changing your ng-repeat to ng-repeat="card in ::cards" will create a bind only until the expression is evaluated, then destroy the listener. This is ideal for situations where you know that the element will never change once it's been evaluated.

The other method is to use a more aggressive tracking on the elements. ng-repeat="card in cards track by $id" will cause the elements to be tracked by the $id field, and angular will be able to smartly remove the listener when the object with the unique $id no longer exists in the DOM.

Watching both of these in the timeline, you will see that the first option Bind Once will spend more time with no listeners, as it will destroy the listeners after evaluation and only spawn new listeners to add the new elements to the DOM. The second option will spend most of it's time at the upper bounds of listeners for your number of active elements, but will drop all the listeners as elements are removed and add new listeners to replace them.

In the end, Bind Once will be more efficient if you know the elements aren't going to change, only be replaced; Tracking will be more flexible if your elements could change between being added and removed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!