实际使用`stackalloc`关键字 [英] Practical use of `stackalloc` keyword

查看:208
本文介绍了实际使用`stackalloc`关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人实际使用 stackalloc 编程时,在C#中?我知道的是什么呢,但唯一一次在我的code显示出来是偶然的,因为智能感知表明它,当我开始输入静态,例如

Has anyone ever actually used stackalloc while programming in C#? I am aware of what is does, but the only time it shows up in my code is by accident, because Intellisense suggests it when I start typing static, for example.

虽然它是不相关的 stackalloc 的使用场景,我实际上做了相当多的遗产互操作在我的应用程序,所以每一个现在,然后我可以诉诸使用不安全 code。但尽管如此,我通常会找到方法来避免不安全完全

Although it is not related to the usage scenarios of stackalloc, I actually do a considerable amount of legacy interop in my apps, so every now and then I could resort to using unsafe code. But nevertheless I usually find ways to avoid unsafe completely.

由于可在.net中一个单独的线程堆栈大小的1Mb〜(纠正我,如果我错了),我甚至使用更多的保留 stackalloc

And since stack size for a single thread in .Net is ~1Mb (correct me if I'm wrong), I am even more reserved from using stackalloc.

有没有一些实际的情况下,人们可以说:这正是数据的右量和处理我去不安全的,并使用 stackalloc

Are there some practical cases where one could say: "this is exactly the right amount of data and processing for me to go unsafe and use stackalloc"?

推荐答案

的唯一理由使用 stackalloc 是性能(无论是计算或互操作)。通过使用 stackalloc ,而不是一个堆分配的数组,你产生更少的GC pressure(GC的需要运行更少),你不需要针阵列下来,它的速度比堆阵分配中,它是在方法退出(GC运行时堆分配阵列只释放)自动释放。而不是本机分配器还可以通过使用 stackalloc (如malloc的或.net同等学历)也获得速度和自动释放范围上的退出。

The sole reason to use stackalloc is performance (either for computations or interop). By using stackalloc instead of a heap allocated array, you create less GC pressure (the GC needs to run less), you don't need to pin the arrays down, it's faster to allocate than a heap array, an it is automatically freed on method exit (heap allocated arrays are only deallocated when GC runs). Also by using stackalloc instead of a native allocator (like malloc or the .Net equivalent) you also gain speed and automatic deallocation on scope exit.

明智的性能,如果你使用 stackalloc 您大大提高缓存命中的CPU上的变化,由于数据的地方。

Performance wise, if you use stackalloc you greatly increase the change of cache hits on the CPU due to the locality of data.

这篇关于实际使用`stackalloc`关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆