mardi 28 avril 2015

Javascript closures and memory leaks with a lot of imbricated functions and callbacks

We are building a large web applications and of course we stumbled upon the problem of having "memory leaks". Basically, when we start we have a memory usage of 90mb. We go to the second page and we get 900 mb(we are loading a lot of data).

Then, we return to the first page, and we still have around 900mb in memory.

We figured out that we probably have some leaks due to the different closures and callbacks we have inside functions. By investigating the code and looking around the web for the best possible solutions or strategies to avoid memory leaks, we found a couple of interesting articles such as these two:

http://ift.tt/1Kqwsld

http://ift.tt/1zkHIP7

Here is an example of what we have in the code:

var drawingSection_; // instantiated elsewhere but global to the file


function createSection() {
 var section = Section.create();

 section.from = drawingSection_.startPoint.data.id;

 var endPoint = drawingSection_.getEndPoint();

 var endPointData = endPoint.data;
 section.to = endPointData ? endPointData.id : '';

 Pubsub.publish(‘openView’, ‘mainView’, section, {
   endPoint: {
     lat: endPoint.leafletObj._latlng.lat,
     lng: endPoint.leafletObj._latlng.lng
   },
   click: {
     cancel: function() {
       selectedItemChanged_(drawingSection_.startPoint);
       drawingSection_.clear();
     }
   },

   callback: {
     ok: function() {
       drawingSection_.clear();
     }
   },
 });
}

Since our code is really huge, it is hard to profile everything so we basically have to manually inspect for memory leaks. In this situation, should we empty section and endpoint somewhere ? Will it make a difference? We have a pubsub that will retain a reference to section and also we have some callbacks functions that are using the data.

What is the guideline in a case like that were we have a lot of different closures ?




Aucun commentaire:

Enregistrer un commentaire