Primary reasons why programming language runtimes use stacks?
Many programming language runtime environments use stacks as their primary storage structure (e.g. see JVM bytecode to runtime example).
Quickly recalling I se开发者_开发知识库e following advantages:
- Simple structure (pop/push), trivial to implement
- Most processors are anyway optimized for stack operations, so it is very fast
- Less problems with memory fragmentation, it is always about moving memory-pointer up and down for allocation and freeing complete blocks of memory by resetting the pointer to the last entry offset.
Is the list complete or did I miss something? Are there programming language runtime environments which are not using stacks for storage at all?
Just decided to include a link to one of the most insightful developers alive (and active), the architect of hotspot JVM:
When you compare the speed & power of a CPU executing bytecodes, you'll see lots of hardware complexity around the basic execution issues (I'm skipping on lots of obvious examples, but here's one: the stack layout sucks for wide-issue because of direct stack dependencies).
http://www.azulsystems.com/blog/cliff-click/2010-04-21-un-bear-able
Yes, there are runtimes that don't use stacks, or at least not the naive model with one stack and the CPU push/pop instructions. Newer languages designed for concurrency/multithreading commonly avoid the single-stack model. The Go language is an example.
One problem with the "hardware stack" is that error handling can be hard when the stack overflows (the handler may have to use stack space itself). Explicitly maintaining a stack in the heap, as a linked list perhaps, avoids this problem, although it means that stack overflow is reduced to heap overflow and an infinite recursion takes longer to detect.
As methods can call other methods which may call others etc., and the storage for each must be maintained until the called method returns, using a stack frame to hold the storage is the obvious solution.
Stack is also used to pass parameters between methods. Typically the parameters will be pushed onto the stack by the caller and then callee will know where the parameters are in the stack (offsetting -ve from the current stack pointer).
精彩评论