G
G
Griboks2018-08-30 12:26:54
.NET
Griboks, 2018-08-30 12:26:54

How to control the memory of tuples?

Good afternoon.
It is necessary to return a data structure from the method. For this, the type of tuples was chosen. During testing, it turned out that garbage collection does not work as expected - a memory leak is created.
How to correctly create, delete and use tuples with minimal memory consumption?

(byte[], byte[]) Test() => (new byte[12345678], new byte[16]);
static void Main(string[] args)
{
   var x = Test();
   for(var i=0;i<10;i++)
      x=Test();
}

Each iteration increases memory consumption by 150 MB. Where is the mistake?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
G
Griboks, 2021-08-13
@Griboks

Tuples, like other value types (and the entire method stack), are not garbage collected until the current method exits.
Therefore, dead references to arrays remain, which prevent the garbage collector from freeing them.

D
DarkByte2015, 2018-08-30
@DarkByte2015

And where did you get that there is a leak? Yes - it increases memory consumption, but what did you expect? You create two arrays at each iteration and the garbage collector does not have time to dispose of them. In my opinion this is normal. Better think about how to optimize the algorithm so as not to create arrays at each iteration. Perhaps it is necessary to rewrite the function so that it accepts references to arrays and fills them inside, and the arrays were created before the loop once.

B
basrach, 2018-08-31
@basrach

In the above example, there is no problem, there cannot be a leak. If there is a 100% leak, then most likely, when you created this example based on real code, you missed an important detail due to which the leak occurs.

S
Serafim Prozorov, 2018-09-01
@serafimprozorov

You allocate a new array for each iteration, so naturally the amount of memory used increases after each iteration.
How to optimize the algorithm depends on the context of your task: what exactly do you do with the received bytes?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question