加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:49:30 所属栏目:百科 来源:网络整理
导读:我一直在努力弄清楚事情在堆栈上的分配,我无法弄清楚你将如何使数组(或其中的值)在堆栈上分配; 在这个例子中: public void foo(){ int bar[] = new int [10];} 堆栈中将分配10个int结构体,只有指向它们的指针才能堆叠,正确吗? 如何使固定大小的数组去堆栈
我一直在努力弄清楚事情在堆栈上的分配,我无法弄清楚你将如何使数组(或其中的值)在堆栈上分配;

在这个例子中:

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进行性能相关的讨论.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读