堆与堆栈分配的含义(.NET) [英] Heap versus Stack allocation implications (.NET)

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

问题描述

来自答案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?

another answer 有人指出堆栈是快点.这是唯一的暗示吗?有人可以给出一个简单的分配位置更改可以解决问题(例如性能)的代码示例吗?

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 中删除.

推荐答案

只要你知道语义是什么,堆栈与堆的唯一后果就是确保你不会溢出堆栈,并且意识到垃圾收集堆是有成本的.

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.)

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

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