I’m working with some code in NodeJS, and some objects (i.e, ‘events’) will be medium-lived, and then discarded.
I don’t want them becoming a memory burden when I stop using them, and I want to know if there is a way to mark an object to be garbage-collected by the V8 engine. (or better yet- completely destroy the object on command)
I understand that garbage collection is automatic, but since these objects will, 60% of the time, outlive the young generation, I would like to make sure there is a way they don’t camp out in the old-generation for a while after they are discarded, while avoiding the inefficiency of searching the entire thing.
I’ve looked around, and so far can’t find anything in the NodeJS docs. I have two main questions:
- Would this even be that good? Would it be worth it to be able to ‘mark’ large amounts of unused objects to be gc’ed? (possibly 100+ at a time)
- Is there even a way to do this?
Anything (speculation, hints, articles) would be appreciated. Thanks!
(V8 developer here.) There’s no way to do this, and you don’t need to worry about it. Marking works the other way round: the GC finds and marks live objects. Dead objects are never marked, and there’s no explicit act of destroying them. The GC never even looks at dead objects. Which also means that dead objects are not a burden.
“Garbage collector” really is a misleading term: it doesn’t actually find or collect garbage; instead it finds non-garbage and keeps it, and everything it hasn’t found it just ignores by assuming that the respective memory regions are free.
In theory, there could be a way to manually add (the memory previously occupied by) objects to the “free list”; but there’s a fundamental problem with that: part of the point of automatic memory management is that automating it provides better security and stability than relying on manual memory management (with programmers being humans, and humans making mistakes). That means that by design, a GC can’t trust anyone else to declare objects as unreachable; it would always insist on verifying that claim — which is equivalent to disregarding it, as the only way to verify it is to run a full regular GC cycle.