Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce/remove memory leaks in Angular application

I am optimizing my large Angular App. As I found a that Google DevTools is very good to detect problems. As I just have started learning about DevTools, I am very confused about memory leaks.

When I move back and from to different pages in my app, Profile heap Snapshot size is increasing again and again so I think there are some object which is not being cleaned by GC and that's why my app is getting slow after sometime so how to solve this. Please help.

Note

This is what I understand using DevTools, please correct me if I am wrong. Other suggestions are welcome.

Till now what I have used

  1. AngularOnce directive for reducing watch whenever required.
  2. QuickList directive to replace ng-repeat with quick-ng-repeat.
  3. InView Directive, to handle large list so I am removing DOM which is not in viewport.
  4. Lazy load approach from ngInfiniteScroll directive.
like image 633
Jay Shukla Avatar asked Mar 14 '14 06:03

Jay Shukla


People also ask

What causes memory leaks in angular?

Here are a few things that might cause memory leaks in an Angular app: Missing unsubscription, which will retain the components in the memory. Missing unregistration for DOM event Listeners: such as a listener to a scroll event, a listener to forms onChange event, etc. unclosed WebSocket connections when they are ...

How do you check if there is a memory leak in angular?

The first thing to do is to open the Chrome Dev Tools, open the panel on the right and click on More Tools > Performance Monitor. The memory of our application is displayed in the blue graph.


1 Answers

  1. Remove bindings to avoid memory leaks, Use Scopes $destroy() Method.

    Note:

    The most likely culprit of memory leak in Angular is JQuery used in your directives. If you attach an event-listener in your directive using a JQuery plugin, the latter would keep a reference to your DOM even after Angular deletes its own reference to the DOM, which means it would never be garbage-collected by the browser, which in turn means “Detached DOM tree” in your memory

    In your Directive keep practice for unbinding the jQuery Event. $destory Method which can be used to clean up DOM bindings before an element is removed from the DOM.

     $scope.$on("$destroy",function() {     $( window ).off( "resize.Viewport" );  });     
  2. Don't Forget To Cancel $timeout Timers In Your $destroy Events In AngularJS

    $scope.$on("$destroy",function( event ) {     $timeout.cancel( timer ); }); 
like image 140
JQuery Guru Avatar answered Sep 22 '22 09:09

JQuery Guru