Hacker News new | ask | show | jobs
by redxdev 1966 days ago
There's an inherent issue with doing that while still being safe: what if there's still a reference to your "big object" somewhere? The only way for the runtime to know for certain it's safe to delete the object is to effectively run the GC anyway. The alternative is that the object gets deleted without any checks and any references to it will now (probably) cause a crash - and it'll be a hard native crash rather than a .net exception since it's outright accessing invalid memory rather than just a "managed" null pointer.

There's probably something to be said for allowing such a thing in explicitly "unsafe" code, but not in the normal runtime. In fact, it might even be possible now by leveraging some of the existing unsafe bits in .net.

1 comments

True but all it takes to fix this is to add if on the reference count of the object. You only need a full scan to handle circular references. You could have a gc.collect(obj) which will collect this object and all of its dependencies provided their reference count has gone to zero. And otherwise do nothing until the next full garbage collection.
There are GCs that take this approach (refcount + sweeps to break cycles). It has tradeoffs however.

- Extra space for every object to have a refcount

- Extra refcount bookkeeping every time you (re)assign a reference (possibly triggering cache thrashing/false sharing in some multithreaded scenarios), xchgs instead of movs, etc.

- Pointless if you're using bump allocators (they can't reuse the 'freed' memory until the next GC cycle compacts memory anyways), so you're forced to use more complicated allocator designs if you're to reuse said memory.

Cycles mean it still doesn't give you 100% deterministic object destruction either, so you want extra mechanisms for disposing unmanaged resources at controlled times ala IDisposable anyways.

There's no reference count on the object. That's not how garbage collection works in .NET, or Java for that matter.
They don't define which algorithms are to be used, and at least in what concerns Java, there are some implementations that experimented with reference counting based GCs.

https://www.microsoft.com/en-us/research/wp-content/uploads/...

But to get the reference count you’d need to run the entire mark phase.