c#什么时候在栈上分配数组?

When is array allocated on stack in c#?

我一直在试图弄清楚什么时候在堆栈上分配东西,但我无法弄清楚如何让数组(或其中的值)在堆栈上分配;

在这个例子中:

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 了解与性能相关的讨论。