我现在正在阅读SICP,并没有真正理解5.5.6 SICP的词法寻址中描述的词法寻址的必要性。
既然它说 “因为我们的语言是词法范围的,所以任何表达式的运行时环境都将具有与表达式出现的程序的词法结构并行的结构”,我认为在运行时环境中搜索变量的成本与在编译环境中搜索。 为什么我们要费心去实现一个编译环境呢? 我认为编译环境将具有与程序的词法结构相同的结构,这与运行时环境相同,不是吗?
最佳答案
词法寻址对于加速变量查找很有用。如果没有词法寻址,查找变量需要遍历当前环境的框架或其封闭环境的框架等等,所有这些都在运行时 - 因为我们不知道变量被绑定(bind)在哪里,如果在全部。书中提到了这一点:
Our compiler, as we have implemented it so far, generates code that uses the lookup-variable-value operation of the evaluator machine. This searches for a variable by comparing it with each variable that is currently bound, working frame by frame outward through the run-time environment. This search can be expensive if the frames are deeply nested or if there are many variables.
相比之下,词法寻址查找过程在编译时准确地知道在哪里查找变量,从而大大减少了查找变量所需的时间:
lexical-address-lookup
takes as arguments an environment and a lexical address that consists of two numbers: a frame number, which specifies how many frames to pass over, and a displacement number, which specifies how many variables to pass over in that frame.Lexical-address-lookup
will produce the value of the variable stored at that lexical address relative to the current environment. If we add thelexical-address-lookup
operation to our machine, we can make the compiler generate code that references variables using this operation, rather thanlookup-variable-value
.
关于compiler-construction - SICP第5章中词法寻址的优点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068508/