I have a recursive function that has many reference variables taking significant amount of memory. I noticed that every stack frame takes around 1MB, so when the function is being called recurrently 100 times it consumes 100MB.
Let's see simplified example below. From the main method I call a recursive method. With every stack frame there is created a reference ('someList') to the new object on the heap. The memory increases (ID 2,3 on the picture). Then when the particular stack frames are beiing popped out the memory is released (ID 4 on the picture).
What I want to do is to dispose created objects for a particular stack frame before it is popped out. At the time when new stack frames are being popped in.
class Program
{
static void Main(string[] args)
{
var testClass = new TestHeapCollection();
Console.WriteLine(testClass.IsSaved(10));
Console.ReadKey();
}
}
internal class TestHeapCollection
{
public bool IsSaved(int a)
{
var someList = new List<string>();
/*
processing data with local variables
*/
return a <= 0 || IsSaved(a - 1);
}
}