A few considerations on garbage collection

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Wed Apr 30 17:02:07 PDT 2014


On Wed, 30 Apr 2014 16:29:38 -0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> On 4/30/14, 11:15 AM, Dmitry Olshansky wrote:
>> It doesn't and CAN'T. As long as there is a pointer into the block it
>> stays. There are plenty of ways to shoot yourself in the foot if this
>> rule is not respected. Anyhow, for starters, a conservative GC doesn't
>> know what is a slice when ptr/length sits in registers!
>
> Yah, if you find a register possibly pointing somewhere in the middle of  
> an array, all bets are off.

I think Dmitry's point is that the GC is not aware of the length portion  
of a slice, only the pointer portion. By definition, a pointer at a block  
could refer to the whole block.

In other words, in your original example, it is aware that 'a' points at  
the block, but not that a's length is 500. Theoretically, you could assume  
that a pointer may only lock all data *after* the pointer in the block. In  
other words, the first 250 ints could be reallocated if not referred to.  
But I think this is too limiting a behavior, for not much gain.

>
> But let's say that's not the case and all that's pointing in a 1M  
> elements int[] is a int[] of 5 elements somewhere in the middle. Do we  
> want to support these?

I think we are never ever going to get away from the requirement of users  
to be at least cognizant of these situations.

Consider this:

int[] x;

x.reserve(1_000_000);

should the GC at this point just refuse, citing its rule that you just  
can't ask for that much memory until you want to use it? Or maybe the GC  
comes along and says "you're not using that, I'm going to take it back,"  
when your goal explicitly is to pre-allocate such data.

> s = s.ptr[-1 .. $ + 1]

I can think of a very important use case that does this -- interfaces.  
Possibly you could allow this exception, but I don't think it's worth  
disallowing a user type that might mimic such useful behavior for some  
low-level purpose.

-Steve


More information about the Digitalmars-d mailing list