Answer the question
In order to leave comments, you need to log in
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();
}
Answer the question
In order to leave comments, you need to log in
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.
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.
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.
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 questionAsk a Question
731 491 924 answers to any question