Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does dequeue'ing an object remove the reference from the Queue object and allow for GC?

Some backgroud:

I am looking at the various collection objects available to me in the .NET framework and trying to make a decision on which one to use.

I have to go through each object in a collection, not necessarily enumerate through them, process, and remove it. I have to do this in memory and the dataset will be large (closing in on a gig). I need my memory footprint to reduce as quickly as possible.

Question: Does dequeue'ing an object from the Queue collection free that reference in the queue so the garbage collector can do its job? (assuming no other reference to the dequeued object)

like image 349
Ryan Bennett Avatar asked Feb 21 '26 12:02

Ryan Bennett


2 Answers

If you're talking about the built-in Queue<T> and Queue collections then yes, when an object is dequeued then the element in the backing array that previously held that object is set to default(T)/null, which should allow the object to be subsequently collected.

like image 198
LukeH Avatar answered Feb 24 '26 06:02

LukeH


Behind the scenes, the Queue class maintain an internal circular array and two variables that serve as markers for the beginning and ending of the circular array: head and tail.

The Enqueue() method starts by determining if there is sufficient capacity for adding the new item to the queue. If so, it merely adds the element to the circular array at the tail index, and then "increments" tail using the modulus operator to ensure that tail does not exceed the internal array's length. If, however, there is insufficient space, the array is increased by a specified growth factor. This growth factor has a default value of 2.0, thereby doubling the internal array's size, but you can optionally specify this factor in the Queue class's constructor.

The `Dequeue()` method returns the current element from the head index. 
It also sets the head index element to null and "increments" head.

So the 'dequeued' object is set to null and later on GCed as needed, although non-deterministic; the times when GC runs can vary.

like image 43
ukhardy Avatar answered Feb 24 '26 04:02

ukhardy