什么时候在c#中的堆栈上分配?

前端之家收集整理的这篇文章主要介绍了什么时候在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进行性能相关的讨论.

原文链接:https://www.f2er.com/csharp/94501.html

猜你在找的C#相关文章