GC, the simple solution

Walter Bright newshound at digitalmars.com
Sun Jun 4 14:42:35 PDT 2006


Frank Benoit wrote:
> The best garbage collector I can think about, is a reference counting
> one.

Reference counting has its advantages, but some severe disadvantages:

1) cyclical data structures won't get free'd

2) every pointer copy requires an increment and a corresponding 
decrement - including when simply passing a reference to a function

3) in a multithreaded app, the incs and decs must be synchronized

4) exception handlers (finally's) must be inserted to handle all the 
decs so there are no leaks. Contrary to assertions otherwise, there is 
no such thing as "zero overhead exceptions."

5) in order to support slicing and interior pointers, as well as 
supporting reference counting on arbitrary allocations of non-object 
data, a separate "wrapper" object must be allocated for each allocation 
to be ref counted. This essentially doubles the number of allocations 
needed.

6) The wrapper object will mean that all pointers will need to be 
double-dereferenced to access the data.

7) Fixing the compiler to hide all this stuff from the programmer will 
make it difficult to interface cleanly with C.

8) Ref counting can fragment the heap thereby consuming more memory just 
like the gc can, though the gc typically will consume more memory overall.

9) Ref counting does not eliminated latency problems, it just reduces them.

The proposed C++ shared_ptr<>, which implements ref counting, suffers 
from all these faults. I haven't seen a heads up benchmark of 
shared_ptr<> vs mark/sweep, but I wouldn't be surprised if shared_ptr<> 
turned out to be a significant loser in terms of both performance and 
memory consumption.

That said, I'd like for D to optionally support some form of ref 
counting, as rc is better for managing scarce resources like file handles.



More information about the Digitalmars-d mailing list