Heap versus Stack allocation implications (.NET)(堆与堆栈分配的含义(.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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:堆与堆栈分配的含义(.NET)
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01