Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak in Angular's $compile?

Summary

Why is the following plunkr causing a memory leak every time $compile runs?

http://plnkr.co/edit/HhB4croPKuN5TP2NPqq6

Explanation to the code

I am writing a directive which sometimes needs to completely re-render its HTML. It does this by generating its template as a string, and then feeding that string to $compile, finally using jQuery to remove the old DOM and replace it with the newly rendered element.

Each time it does this, the application leaks several megabytes of memory, often crashing the browser. The Chrome heap snapshot shows a tree of detached DOM elements gets added each time, but the Plunkr for some reason does not have this issue (although it still leaks a lot).

What am I doing wrong that causes this memory leak?

"What? Generating a string template and re-compiling it? Why?"

This is clearly not the way Angular directives are meant to be written, I know. My first approach would be a combination of ng-repeats with other two-way binding. Unfortunately, this causes performance issues as the number of $watch-statements on the scope increases. For a bit of reasoning as to why I chose this approach, I give a small rant about it here: How does data binding work in AngularJS?

EDIT

I have been working on the plunk, and it no longer leaks memory. I'll keep this question around, in case anyone else finds it useful as a non-leaking method for re-compiling DOM.

like image 571
MW. Avatar asked Sep 30 '13 10:09

MW.


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.


1 Answers

Answered it myself to make sure it doesn't crop up under "unanswered". I have been working on the plunk, and it no longer leaks memory. I'll keep this question around, in case anyone else finds it useful as a non-leaking method for re-compiling DOM.

like image 65
MW. Avatar answered Oct 18 '22 12:10

MW.