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

标签 c# arrays heap-memory allocation stack-memory

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

在这个例子中:

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/

相关文章:

堆/栈的 C++ 标准术语

c - 在 C 中实现链表的设计选择

c# - Excel 文档的 OpenXml SDK 2.0 中的卡住 Pane

c# - 使用 sharpcompress 创建一个 7zip 压缩包

c# - 如何在 UWP ListView 的最后一列中添加文本框?

c# - 在控制台打印数组

javascript - 如何根据Javascript中的特定条件从数组中删除一行

c++ - 我如何判断 CString 是在堆上还是在堆栈上分配内存?

c# - Lambda 表达式,其中列等于列表项

arrays - Bash 移位更改关联数组的期望值