In a very interesting post from 2001 Allen Wirfs-Brock explains how to implement block closures without reifying the (native) stack.
From the many ideas he exposes there is one that I don't quite understand and I thought it would be a good idea to ask it here. He says:
Any variable that can never be assigned during the lifetime of a block (e.g., arguments of enclosing methods and blocks) need not be placed in the environment if instead a copy of the variable is placed in the closure when it is created
There are two things I'm not sure I understand well enough:
- Why using two copies of the read-only variable is faster than having the variable moved to the environment? Is it because it would be faster for the enclosing context to access the (original) variable in the stack?
- How can we ensure that the two variables remain synchronized?
In question 1 there must be another reason. Otherwise I don't see the gain (when compared with the cost of implementing the optimization.)
For Question 2 take a non argument that is assigned in the method and not in the block. Why the oop stored in the stack would remain unchanged during the life of the block?
I think I know the answer to Q2: Because the execution of the block cannot be intertwined with the execution of the method, i.e., while the block lives, the enclosing context does not run. But isn't there any way to modify the stack temporary while the block is alive?