.net 中的堆栈操作

Stack manipulation in .net

想深入了解CLR是如何维护线程的栈的。 如果我们创建一个基于值的 var1 CLR 将这个结构直接放在堆栈的顶部,然后可以将其他一些对象添加到堆栈的顶部。

所以问题是对 var1 的操纵是如何发生的。如果我们用一个新值覆盖这个变量,CRL 应该从堆栈的顶部开始(对堆栈顶部的引用应该保存在一些缓存中)并用一个新的对象更新那个对象。所以如果这个变量在堆栈的顶部,这个操作理论上应该更快。差异应该很小,但它的维护方式很有趣。

int var1 = 10;
var1 += 30;//should be theoretically faster because CLR shouldn't go deeper into the stack to replace value
int var2 = 20;
//other variables

-----------------

int var1 = 10;
int var2 = 20;
//other variables
var1 += 30;//should be theoretically slower because CLR should go deeper into the stack to replace value

我的假设是正确的还是我遗漏了一些细节?

访问堆栈的不同部分没有性能差异。更改值时不涉及推动或弹出。直接访问内存位置,即使它位于堆栈上。堆栈只是内存,就像其他任何东西一样。变量与内存地址关联,该内存地址用于读取或写入值。