堆和栈分配的影响(.NET) [英] Heap versus Stack allocation implications (.NET)

查看:146
本文介绍了堆和栈分配的影响(.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从<打击> <一个href="http://stackoverflow.com/questions/423823/whats-your-favorite-programmer-ignorance-pet-peeve#answer-424035">SO回答 1 有关堆和栈,它提出了我一个问题:为什么它重要的是要知道的变量分配

From an SO answer1 about Heap and Stack, it raised me a question: Why it is important to know where the variables are allocated?

另一个答案有人指出,该堆栈快点。这是唯一的含义?可能有人给code例子,一个简单的分配位置变化可能会解决问题(如性能)?

At another answer someone pointed that the stack is faster. Is this the only implication? Could someone give a code example where a simple allocation location change could solve a problem (eg. performance)?

请注意,这个问题是.Net的

1这个问题从SO删除。

推荐答案

所以,只要你知道什么是语义,堆栈VS堆的唯一后果是确保你不会溢出堆栈,并成为而言注意,有垃圾收集堆相关的成本。

So long as you know what the semantics are, the only consequences of stack vs heap are in terms of making sure you don't overflow the stack, and being aware that there's a cost associated with garbage collecting the heap.

例如,JIT的可以的通知,对新创建的对象从来没有使用当前方法之外(参考无法逃避其他地方),并为它分配在堆栈中。它没有这样做,在那一刻,但它是一个合法的事情。

For instance, the JIT could notice that a newly created object was never used outside the current method (the reference could never escape elsewhere) and allocate it on the stack. It doesn't do that at the moment, but it would be a legal thing to do.

同样,C#编译器的可以的决定分配在堆上所有局部变量 - 将通过该执行堆栈将只包含一个参考MyMethodLocalVariables的一个实例和所有变量访问。 (事实上​​,代表们或迭代块捕获的变量已经有这样的行为。)

Likewise the C# compiler could decide to allocate all local variables on the heap - the stack would just contain a reference to an instance of MyMethodLocalVariables and all variable access would be implemented via that. (In fact, variables captured by delegates or iterator blocks already have this sort of behaviour.)

您的问题上来,而埃里克利珀正在审查中的深度C# - 我有一个部分解释什么飞到哪里,在C#1,他估摸了的开发者不应该关心

Your question came up while Eric Lippert was reviewing C# in Depth - I have a section explaining what goes where in C# 1, and he reckoned that developers shouldn't care.

这篇关于堆和栈分配的影响(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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