How to avoid memory leaks in applications using angular?

I tried to find if my angularjs code has a memory leak but not yet found.

I have read several articles on javascript memory-leak, but this is not useful for angularjs application as it uses bi-binding which hide most of DOM operation for users.

So, I have one more question: how to write a memory leak application using angular? Is there a general mistake we should avoid?

+4
source share
3 answers

Angular basically handles it for you, but there are places where you need to think about memory. Since your services exist from the moment of their creation, when your application is closed, it is easy to drill memory into such objects. As if you were caching, you could get cached references to objects that will never be used again, so you need a strategy to release those objects.

Another place in directives is where you interact with the DOM. But while you're listening to $scope.$on('$destroy', function () { /* Clean up code here */ }); and cleanse yourself, you must be in order.

+7
source

If you use $ timeout to execute a function that does not return null, you will get a memory leak. This is very easy to do in coffeescript, as it implicitly returns the value of the last line of the function

eg.

 doSomethingEveryTenSeconds = -> //do something here $timeout(doSomethingEveryTenSeconds, 10000) null #prevent memory leak 
+4
source

To answer that, you really need to know the Angular garbage collection. This is a really good job. But if he believes that there is a reference to the object or if something else refers to it, a memory leak may occur. You can use jQuery or any other library to create a circular reference through a DOM object.

Here is an example. http://plnkr.co/edit/nIt78S?p=preview

If you open controllers.js, you will see a jQuery $() to Angular $scope circular link:

 //*** CREATING MEMORY LEAK *** $("#memory-leak").on('click', function() { console.log("[HomeController " + myInstance + "] click()"); $scope.data.counter++; }); 

Since the jQuery.on () method is bound to a div outside the controller, it is never freed. You can check this out:
1) Opening the console
2) Moving between the "Home" and "Data" pages. Each time you do this, note that a new instance of Home Controller is created.
3) After you have created 3 or 4 instances, click on the div that says โ€œMemory leak testโ€. You will see 3 or 4 console logs from the above code, a memory leak!

+1
source

All Articles