3

Recetly I was looking for memory leaks in my javascript code. Ater finding some major leaks I starter to look for minor and found something that could be a potential leak - the "hoverIntent.js" plugin. I would like to ask if this is really a leak or am I a bit too overzealous?

General schema fo the code (full code here http://cherne.net/brian/resources/jquery.hoverIntent.js):

(function($) {
    $.fn.hoverIntent = function(f,g) {

    //...


    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    var compare = function(ev,ob) {
        //... function body
    };


    var delay = function(ev,ob) {
       //... function body
    };


    var handleHover = function(e) {
      //... function body
    };


    return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
    };
})(jQuery);

I know that many js plugins are written that way, but... If I get that correctly every time I invoke hoverIntent on my object, 3 new functuions (closures) are created? Isn't it a possible memory leak (or at least a performace issue)?

Wouldn't it be better to write is this way:

(function($) {

  //create the methods only once on module init?

    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    var compare = function(ev,ob) {
        //... function body
    };


    var delay = function(ev,ob) {
       //... function body
    };


    var handleHover = function(e) {
      //... function body
    };


    $.fn.hoverIntent = function(f,g) {
            //no closures here
    return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);

    };
})(jQuery);
dstronczak
  • 2,406
  • 4
  • 28
  • 41
  • 1
    I suggest you use this for your jQuery plugins: http://jqueryboilerplate.com/ – elclanrs Jan 28 '13 at 08:59
  • similar question [does-creating-functions-consume-more-memory](http://stackoverflow.com/questions/7451279/does-creating-functions-consume-more-memory). – t.niese Jan 28 '13 at 09:23

1 Answers1

2

You are correct, your second example would use less memory because of less closure functions. But as soon as you event isn't callable (element removed etc.) they would disappear again so it is not a "leak" as the memory isn't lost forever.

Also many plugins use the closure by setting the current state of an element in a variable instead of the element itself.

Nemo64
  • 2,535
  • 3
  • 20
  • 24