Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs 1.5 : How to identify what is getting leaked and fix the leak?

Tested in chrome latest and other browsers. This page starts a timer() to refresh every 60 seconds. On init() and every refresh(), it gets data from the server and display the same in the page. We see that it leaks lot of MB every refresh.

  1. Now, how do I identify the specific objects and/or DOM Nodes that are being leaked

  2. Once I identify the object/Nodes from #1, how do I go about fixing the leaks ?

Are there any books, good tutorials that would cover the above for Angularjs 1.5 ?

like image 736
anjanb Avatar asked Aug 11 '17 06:08

anjanb


2 Answers

You probably found https://developers.google.com/web/tools/chrome-devtools/memory-problems/ and http://www.dwmkerr.com/fixing-memory-leaks-in-angularjs-applications/ as there are no more detailed resource out there.

A DOM node can only be garbage collected when there are no references to it from either the page's DOM tree or JavaScript code. A node is said to be "detached" when it's removed from the DOM tree but some JavaScript still references it. Detached DOM nodes are a common cause of memory leaks.

  1. If you're not holding a reference of the timer but creating a new timer on every refresh - leak, solvable by reusing the $timeout

  2. Checkout - CTRL + F $scope is retained by a context for a closure. on second provided link. The use case explained there is so similar to one you're having. Further on in the article:

We can open the function and examine it for issues. There's an $http.get which has as closure which uses $scope, but alarmingly there is an $interval registered to run every 10 seconds, which is never deregistered. The interval callback uses another $http.get, with a closure that uses $scope. This is the problem.

If none of the above applies then here's the list of open issues in AngularJS having memory leak as a keyword:

https://github.com/angular/angular.js/issues?utf8=%E2%9C%93&q=is%3Aopen%20memory%20leak

like image 185
maljukan Avatar answered Nov 05 '22 05:11

maljukan


I am not sure if this will help you are not(maybe you've already looked into it), but it is worth mentioning. I had a similar issue with a previous application where objects were continuously being duplicated during every ajax request. So from the load of the page i would be using about 50mb of memory, but after making 10-15 ajax calls the memory would sky rocket to >1gb.

I was able to identify and resolve the issue using chrome dev tools -> memory tab. Through here you are able to record allocation profiles of memory and get a heap snapshot. So, for your situation i might cut the timer down to 5 or 10 seconds for testing purposes, then run these profilers. You will be able to get a view of what methods are being called and at what cost.

Hope this helps.

like image 23
reedb89 Avatar answered Nov 05 '22 05:11

reedb89