Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we call TrimToSize method of a Queue?

Tags:

c#

queue

The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize.

This is written in MSDN Queue Document

Now the question is that in a queue if we add around 20 thousand items then one by one that queue is De-queued until the queue is empty. If we don't call TrimToSize function then the queue size will remain to that 20 Thousand but the data is removed by the garbage collector so technically there is no memory leak and if we check the count or serialize the queue the size is of an empty queue. So why should we call TrimToSize function ?

like image 401
Basit Anwer Avatar asked Sep 15 '25 23:09

Basit Anwer


1 Answers

You are confusing the GC of the objects in the queue with the "slots" of memory for the queue itself.

The queue will have allocated space to store all the 20K references.... those slots will just be empty, and therefore not pointing to objects which are taking up yet more memory. But those "slots" will sstill be there, waiting to have references assigned to them.

like image 183
Andrew Barber Avatar answered Sep 17 '25 12:09

Andrew Barber