Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding AngularJS and Google Chrome memory management

i was wondering why - even on the simple SPA application with AngularJS there seems to be a DOM leakage. I may be misinterpreting this but the way I look at this is that DOM elements allocated are not being released properly. The procedure to reproduce is as follows:

  • navigate to the page on the screenshot with simple AngularJS application
  • turn on timeline recording in developer tools
  • force garbage collection
  • add an item, and then remove it
  • force garbage collection
  • repeat last two steps for atleast 3 times

On the screenshot you can see that after you add an item and remove it there seems to be two more DOM elements more after garbage collection(jump from 502 to 504 DOM elements).

I was hoping that someone could shed some light on this before i get deeper on investigating what is happening. Reason for this test was more complicated AngularJS SPA that I am working on and which also seems to leak memory.

simple angularjs memory consumption timeline

like image 347
Dario Filipović Avatar asked Mar 08 '14 14:03

Dario Filipović


1 Answers

I'm doing a similar thing now. What I've noticed is a couple of things: 1) look at any usage of $(window).fn() -- where fn is any of the functions on the window object; if you're doing that more than once you're adding multiple event handlers to the global object which causes a memory leak

2) $rootScope.$watch() -- similarly, if you're doing this more than once (say, when loading a directive) then you're adding multiple handlers to the global object

3) In my tests (where I go back and forth between two pages) it seems that chrome consumes a large amount of memory (in my case, almost 1GB) before garbage collection kicks in. Maybe when you click the "garbage collection" chrome is not actually doing a GC? Or it's GC for javacsript but not for dom elements?

4) If you add an event handler to the dom element, then remove it from the dom, the handlers never get GC'ed.

like image 79
Robert Hanson Avatar answered Nov 12 '22 11:11

Robert Hanson