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)
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
