我从一篇较早的StackOverflow文章中读到了一个关于何时使用stackalloc的例子。现在这个例子让我有点困惑:
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.
}现在,如果我错了,请随时纠正我,因为我仍然是C#和一般编程方面的新手。但是字节值类型不是吗?值类型不是存储在声明它们的位置吗?这不意味着,在本例中,managed也存储在堆栈上,并且扩展到堆栈帧完成并进入调用入口时,内存被自动清理,因此managed应该以与本例中的unmanaged相同的方式被删除?
发布于 2014-04-22 20:07:50
孤立的字节确实是值类型,但是数组是引用类型。这里指向managed的指针存储在堆栈中,与整个unmanaged变量相同,但是在垃圾收集器运行之前,数组占用的内存不会被回收。
发布于 2014-04-22 20:34:00
byte[]类型看起来类似于stackalloc byte[100],但它所代表的是完全不同的东西。byte[]保存对类型从System.Array派生的堆对象实例的引用,而stackalloc byte[100] (以及,也就是fixed byte[100];)包含100个字节。期望byte[]类型的代码将只接受堆对象引用;它不会直接接受100个字节。与所有引用类型一样,只要引用本身存在,就保证存在任何类型引用的System.Array实例存在(如果发现对象只能通过弱引用访问,则这些引用将在对象停止存在之前失效,以保持此不变)。如果在当前堆栈帧之外的任何地方没有存储对数组的引用,则在堆栈帧退出后,它将停止存在,但如果引用存储在其他地方,则该数组将在任何引用存在的情况下存活。
https://stackoverflow.com/questions/23229096
复制相似问题