javascript - jQuery memory leak patterns and causes -
what of standard issues or coding patterns in jquery lead memory leaks?
i have seen number of questions related ajax() call or jsonp or dom removal on stackoverflow. of jquery memory leak questions focussed on specific issues or browsers , nice have listing of standard memory leak patterns in jquery.
here related questions on so:
- why jquery leak memory badly?
- simple jquery ajax call leaks memory in internet explorer
- memory leak involving jquery ajax requests
resources on web:
from understand, memory management in javascript accomplished reference counting - while reference object still exists, not deallocated. means creating memory leak in single page application trivial, , can trip of use coming java background. not specific jquery. take following code example:
function myobject = function(){ var _this = this; this.count = 0; this.getandincrement = function(){ _this.count++; return _this.count; } } for(var = 0; < 10000; i++){ var obj = new myobject(); obj.getandincrement(); }
it normal until @ memory usage. instances of myobject never deallocated while page active, due "_this" pointer (increase max value of see more dramatically.). (in older versions of ie never deallocated until program exits.) since javascript objects may shared between frames (i don't recommend trying temperamental.), there cases in modern browser javascript objects can hang around lot longer meant to.
in context of jquery, references stored save overhead of dom searching - example:
function run(){ var domobjects = $(".myclass"); domobjects.click(function(){ domobjects.addclass(".myotherclass"); }); }
this code hold on domobject (and contents) forever, because of reference in callback function.
if writers of jquery have missed instances internally, library leak, more client code.
the second example can fixed explicitly clearing pointer when no longer required:
function run(){ var domobjects = $(".myclass"); domobjects.click(function(){ if(domobjects){ domobjects.addclass(".myotherclass"); domobjects = null; } }); }
or doing lookup again:
function run(){ $(".myclass").click(function(){ $(".myclass").addclass(".myotherclass"); }); }
a rule of thumb careful define callback functions, , avoid nesting possible.
edit: pointed out in comments erik, use pointer avoid unnescessary dom lookup:
function run(){ $(".myclass").click(function(){ $(this).addclass(".myotherclass"); }); }
Comments
Post a Comment