所以我现在正在学习MSIL来学习调试我的c# . net应用程序。

我一直在想:堆栈的目的是什么?

把我的问题联系起来: 为什么要从内存转移到堆栈或“加载”? 另一方面,为什么要从堆栈转移到内存或“存储”? 为什么不把它们都放在内存里呢?

是因为它更快吗? 是因为它是基于内存的吗? 效率呢?

我试图抓住这一点,以帮助我更深入地理解CIL代码。


当前回答

通过使用连续传递的编码风格,可以让系统在没有堆栈的情况下工作。然后调用帧成为在垃圾回收堆中分配的continuation(垃圾回收器将需要一些堆栈)。

参见Andrew Appel的旧文章:使用延续和垃圾收集进行编译可以比堆栈分配更快

(由于缓存问题,他今天可能会有一点错误)

其他回答

请记住,当您谈论MSIL时,您是在谈论虚拟机的指令。. net中使用的虚拟机是基于栈的虚拟机。与基于寄存器的虚拟机相反,Android操作系统中使用的Dalvik虚拟机就是一个例子。

The stack in the VM is virtual, it is up to the interpreter or the just-in-time compiler to translate the VM instructions into actual code that runs on the processor. Which in the case of .NET is almost always a jitter, the MSIL instruction set was designed to be jitted from the get go. As opposed to Java bytecode for example, it has distinct instructions for operations on specific data types. Which makes it optimized to be interpreted. An MSIL interpreter actually exists though, it is used in the .NET Micro Framework. Which runs on processors with very limited resources, can't afford the RAM required to store machine code.

实际的机器代码模型是混合的,既有堆栈又有寄存器。JIT代码优化器的一项重要工作是找到方法将栈上的变量存储在寄存器中,从而大大提高执行速度。而Dalvik抖动则有相反的问题。

The machine stack is otherwise a very basic storage facility that has been around in processor designs for a very long time. It has very good locality of reference, a very important feature on modern CPUs that chew through data a lot faster than RAM can supply it and supports recursion. Language design is heavily influenced by having a stack, visible in support for local variables and scope limited to the method body. A significant problem with the stack is the one that this site is named for.

如果不遵循堆栈/堆的概念,数据被加载到随机内存位置或数据从随机内存位置存储…它将是非结构化和无管理的。

这些概念用于以预定义的结构存储数据,以提高性能、内存使用……因此被称为数据结构。

To add a little more to the stack question. The stack concept derives from CPU design where the machine code in the arithmetic logic unit (ALU) operates on operands that are located on the stack. For example a multiply operation may take the two top operands from the stack, multiple them and place the result back on the stack. Machine language typically has two basic functions to add and remove operands from the stack; PUSH and POP. In many cpu's dsp's (digital signal processor) and machine controllers (such as that controlling a washing machine) the stack is located on the chip itself. This gives faster access to the ALU and consolidates the required functionality into a single chip.

维基百科上有一篇非常有趣/详细的文章,堆栈机器指令集的优点。我需要完全引用它,所以简单地放一个链接更容易。我将简单地引用副标题

非常紧凑的目标代码 简单的编译器/简单的解释器 最小处理器状态

通过使用连续传递的编码风格,可以让系统在没有堆栈的情况下工作。然后调用帧成为在垃圾回收堆中分配的continuation(垃圾回收器将需要一些堆栈)。

参见Andrew Appel的旧文章:使用延续和垃圾收集进行编译可以比堆栈分配更快

(由于缓存问题,他今天可能会有一点错误)