My current project includes a vegetation simulation, capable of rendering a large number of instanced tree models that grow and reproduce over time.
I'm currently getting consistent OutOfMemory exceptions on this line of code
if (treeInstances.Length <= currentIndex)
Array.Resize(ref treeInstances, currentIndex + 500);
This code runs when the simulation exceeds the usual bounds of the treeInstances array, and causes it to allocate a new array with an additional 500 slots for trees.
Given that I can see the size of the array when it fails (usually somewhere between 3000 and 5000 instances) and the size of the TreeInstance struct (20 floats), I'm sure my problem lies not in the raw size of the array. Even considering that it has to be temporarily doubled during the resize/8 process (since Array.Resize() allocates a new array) that's still less than half a MB assuming my math is right.
I assume therefore that there must be something I'm missing. Is there some reason the old arrays might not be removed by the garbage collector?
Further Details:
TreeInstanceis a simple struct, with the transform matrix and colour of each tree.treeInstancesis aTreeInstance[]array. It is only used directly here, in the lines of code above.treeInstancesalso has a Property,TreeInstances, which accesses it viaget;set;TreeInstancesis used to set the transform matrix and colour of each tree as it grows, and is fed into the Instancing methods as part of theDrawroutine.- The Instancing methods I'm less familiar with, but perform a variety of functions with
TreeInstanceswithout modifying it's contents (including using it as the source in aDynamicVertexBuffer.SetDataoperation).