function BigObject() {
  var a = '';
  for (var i = 0; i <= 0xFFFF; i++) a += String.fromCharCode(i);
  return new String(a); // Turn this into an actual object
}

// iife 1 / window gets compressed into w
(function (w, $) {
    var x = new BigObject();
    $("#foo").click(function () {
      w._gaq.push("foo");
    });
})(window, window.jQuery);

// iife 2 / window reference left global
(function ($) {
    var x = new BigObject();
    $("#foo").click(function () {
      window._gaq.push("foo");
    });
})(window.jQuery);

Given my minimal understanding of garbage-collection and how items are held in memory, it seems like 1 might cause some memory issues when compared with 2. More of an academic question at this point than an actual bottleneck... Ball help?

有帮助吗?

解决方案

You're thinking of garbage collection backwards. Broadly speaking, things are marked as garbage when you can't trace from a root to them. Having a local reference to the global object does not mean the global object has a reference to you, so it doesn't affect the lifetime of anything.

其他提示

If you were to do this the other way:

(function (w) {

    var name = "bob",
        obj1 = { a : 1, b : 2 },
        obj = (function () {
            var a = obj1,
                return { items : a, getName : function () { return name; } };
        }());

    w.thing = obj;
}(window));

Now you're running into garbage-hindrances. Window has a reference to obj. Obj has a reference to obj1, and has a function with a reference to name...

...so none of the stuff inside of either of these closure is garbage-collectable, until the program has absolutely no references left of window.thing.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top