在这个例子中:
public void foo() { int bar[] = new int [10]; }
堆栈中将分配10个int结构体,只有指向它们的指针才能堆叠,正确吗?
如何使固定大小的数组去堆栈?如果我使用我定义的水道怎么办?
如果我想要将数组大小作为参数传递给函数呢?
解决方法
10 int structs would be allocated on the the heap,only pointer to them would be on stack,correct?
是,对的.
How would one make fixed size array to go on stack? What if I’m using stucts I defined?
stackalloc
keyword服务于此.然而,这仅在不安全的背景下工作,这在大多数情况下是一个相当不必要的限制因素,不值得性能折衷.
例:
public void unsafe foo() { int* bar = stackalloc int [10]; }
您将不得不使用pointer arithmetic访问阵列的成员.
What if I want array size passed as parameter to function?
As far as I understand there should be no problem to get array of arbitrary size on stack when function is called,if size is known when function is called.
按预期工作:
public void unsafe foo(int length) { int* bar = stackalloc int [length]; }
Should I even be bothered by this? As far as I understand getting this fixed size array on stack would improve performance,because no heap allocation is done.
不,一般不是.除非您处理一些非常具体的性能关键场景,例如重型数学计算,加密,压缩等,这样做并没有真正的好处.
另请参阅this question进行性能相关的讨论.