1

Based on this answer, this will "load all the keys into memory":

Object.keys(o).forEach(function(key) {
  var val = o[key];
  logic();
});

Is the memory "freed" when this is done? Or does something need to be "nulled", or the like?

Community
  • 1
  • 1
sun ra
  • 35
  • 5
  • 1
    What would be nulled? There's no variable referencing the list of keys. –  Jul 13 '16 at 16:57
  • It will load them into memory, but after the function each key will go out of scope, so they can be garbage collected. – 4castle Jul 13 '16 at 17:02
  • @4castle Does that mean that they *will* be gc? I.e., this will *not* cause a memory leak on its own? – sun ra Jul 13 '16 at 17:09
  • Technically we don't know if the keys will be GC'd, because as far as we know, the implementation keeps the list around for its own purpose, but if it does, it's outside your control and concern. –  Jul 13 '16 at 17:10
  • @sunra It won't cause a memory *leak* but there's no guarantee as to when that memory will be released. – Mike Cluck Jul 13 '16 at 17:10
  • ...the only thing you need to be concerned about in modern engines is if you manually create permanent references or if you use libraries that create such references without you knowing, like jQuery does. –  Jul 13 '16 at 17:12

1 Answers1

1

Yes, the memory will be freed implicitly after the forEach has completed, as afterwards nothing on the stack will reference the array created by Object.keys any more. (There is no variable to nullify, btw)

You could've written equivalently

{
    const keys = Object.keys(obj);
    keys.forEach(function(key) {
        const val = o[key];
        logic();
    });
}

where it is a bit more obvious that the whole keys array is hanging around during the iteration (in contrast to a "lazy" for in enumeration), and also that it goes out of scope immediately after (when the block ends).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375