我一直在试图弄清楚什么时候在堆栈上分配东西,但我无法弄清楚如何让数组(或者更确切地说是其中的值)在堆栈上分配;
在这个例子中:
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用于与性能相关的讨论。
关于c# - c#什么时候在栈上分配数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274102/