I read an example from an older StackOverflow post about when to use stackalloc. Now this example has me a bit puzzled:
public unsafe void DoSomeStuff()
{
byte* unmanaged = stackalloc byte[100];
byte[] managed = new byte[100];
//Do stuff with the arrays
//When this method exits, the unmanaged array gets immediately destroyed.
//The managed array no longer has any handles to it, so it will get
//cleaned up the next time the garbage collector runs.
//In the mean-time, it is still consuming memory and adding to the list of crap
//the garbage collector needs to keep track of. If you're doing XNA dev on the
//Xbox 360, this can be especially bad.
}
Now feel free to correct me if I'm wrong, as I'm still quite a novice in C# and programming in general. But aren't bytes value types? And aren't value types stored where they are declared? Doesn't this mean that in this example, managed
is also stored on the stack, and by extension when this stack frame finishes and it goes to the calling adress the memory is cleaned up automatically and therefore managed
should be removed in the same manner as unmanaged
in this example?
Isolated bytes are indeed value types, but arrays are reference type. The pointer to managed
here is stored on the stack, same as the entire unmanaged
variable, but the memory consumed by the array isn't reclaimed until the garbage collector runs.