21

If I have an object that would normally be garbage collected, but has been logged to the console, will it still be eligible for garbage collection?

(function(){
  var o = { foo: {} }; 
  console.log(o);
}())

// Can o be collected?

If yes, are there any circumstances where writing to the console (using any of its methods) can affect eligibility for garbage collection?

Edit: I dont believe it will affect eligibility for collection based on watching the heap in Chrome dev tools. But will any category of writing to the console do so?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 5
    Chrome sometimes adds a note to logged objects, something like "evaluated upon first expansion". This suggests that the object might have been GCd in the meantime. But it could also just refer to modifications. – Thomas Mar 03 '15 at 18:52
  • @Thomas I'm pretty sure it's referring to modifications. – Scimonster Mar 03 '15 at 18:56

1 Answers1

6

If you log an object to the console it can not be garbage collected.

You can verify this by entering in the chrome console:

var Foo = function() {};
console.log(new Foo());

Go to “Profiles” and “Take Heap Snapshot”. This will do a garbage collection automatically. Search for class “Foo”. There will be a 1 in column “Objects count“.

hhelwich
  • 200
  • 6
  • My own experiments came to the opposite conclusion by looking at the heap allocated memory. Steps to repro: open dev tools, force a garbage collection, run your code, force a garbage collection. My tests showed the allocated memory was freed. I could however be misguided. – Ben Aston Mar 04 '15 at 20:12
  • Did you take a heap snapshot after the last garbage collection? – hhelwich Mar 05 '15 at 17:43
  • I am using Google Chrome 41.0.2272.76 (64-bit) on Linux. What is your Chrome version? – hhelwich Mar 10 '15 at 17:59
  • @hhelwich '“Take Heap Snapshot”. This will do a garbage collection automatically' using Chrome `Version 79.0.3945.117 (Official Build) (64-bit)` this statement doesn't seem to be true (anymore). I took a Heap snapshot, there were objects present that I believed should have been GC'ed, I manually 'Collected garbage' and took another heap snapshot and they vanished. – Morvael Jan 14 '20 at 09:00