Is GC smart enough not to reallocate?

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 16 07:07:51 PDT 2016


On 6/16/16 9:54 AM, MMJones wrote:
> Suppose one has something like
>
> class foo
> {
>    int[] x;
>    void bar()
>    {
>       x = [];
>    }
> }
>
> Does the GC trash the "cache" when calling bar or does it realize that
> it can use the same memory for x and essentially just shortens the array?

If you reassign x, the compiler does not know enough context to assume 
nothing else has a reference to x's old data. So no, it would not re-use 
that same data.

> Is it equivalent to setting length = 0?

Even this is not going to overwrite the data. You'd need to do:

x.length = 0;
x.assumeSafeAppend;

> I'm a bit worried that setting a managed array to [] might cause a
> completely new reallocation, which is unnecessary and undesirable.

Use assumeSafeAppend when you need to do this.

BTW, x = [] is equivalent to x = null. So this is most certainly going 
to cause a new allocation on the next append.

-Steve


More information about the Digitalmars-d mailing list