In your case, I would allocate one buffer array. For example, select an array of 10 MB in size and fill it with the necessary data. Then, when you move on to the next object, just reuse the array. If you need a more massive array, you can simply allocate a new, larger array and use it instead. The garbage collector will eventually delete your smaller one.
You can also use List<T> , it will internally do the same (select the array, keep it until it gets too small, select the new one). Just Clear before creating the next object.
Note that you cannot force garbage collector 1 to collect an object. IDisposable really only used to clean unmanaged resources, as the garbage collector does not know about them or closes it (file). Calling Dispose does not guarantee (or imply) that the object is deleted from memory.
However, if you do not change anything, your code will still be correct and will work correctly. The garbage collector is responsible for removing unused objects whenever it looks like this, and this ensures that a lot of memory is available at any time. The only thing you need to do for the collector to do his job is to release any links to old objects (by rewriting them or setting them to null or allowing them to exit the scope).
1 ) You can force the garbage collector to collect your data by calling GC.Collect() . However, this is not recommended. Let the garbage collector think for himself.
Virtlink
source share