shifting array slices

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 11 11:02:43 PST 2012


On Saturday, February 11, 2012 10:51:36 H. S. Teoh wrote:
> This brings up an interesting point: what does the GC do if you have an
> array that's continually appended to, and also shrunk from the front?
> That is:
> 
> 	ubyte[] buf;
> 	while ( ... ) {
> 		consumeData(buf[0]);
> 		buf = buf[1 .. $];
> 
> 		ubyte x = getMoreData();
> 		buf ~= x;
> 	}
> 
> Will such a program "leak memory" in the sense that the memory chunk
> allocated to buf will grow larger and larger, even though its initial
> segment is never accessed again? Or is the GC smart enough to only
> reallocate the needed size when the memory chunk is moved (at some point
> when it has no more space to append x)?
> 
> If the GC is smart enough, then this kind of construct could be used
> instead of copying overlapping ranges.

The memory blocks don't grow. When an array no longer has enough room to 
increase its size, and you append to it, a new block is allocated, and the 
array is moved to there. Any slices which refer to the original block still 
refer to it. And when a garbage collection cycle is run and a memory block has 
no references to it, it's collected. The only "leaking" that occurs is that 
once no more slices refer to a particular portion of a memory block, that 
portion is no longer accessible until the block has been recycled.

If you haven't read this article yet, you really should:

http://www.dsource.org/projects/dcollections/wiki/ArrayArticle

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list