Re: Is "pop static 19" inefficient by nature?

Posted by dolomiti7 on
URL: http://nand2tetris-questions-and-answers-forum.52.s1.nabble.com/Is-pop-static-19-inefficient-by-nature-tp4037400p4037401.html

Unlike locals, arguments and fields, static variables are accessed with absolute addressing. It refers to a reserved area in the memory between offset 16 and 255, allowing 240 static variables in total. Which one of the 240 available addresses is allocated to a specific variable will be decided by the assembler and not the VM translator. The only thing you have to do is to converting the number of the static variable which is unique inside the class/VM file into a symbol that is unique inside the program. According to the convention this is done by appending the number to the class name separated by a dot (I.e. Output.19 if you are referencing static 19 in class Output). There is no need to calculate the actual memory address at this point, you can just load the address directly into A with @Output.19 in this example.

Though it would be possible to calculate and allocate all the addresses of static variables inside the VM translator instead of the Assembler, this is not the convention of nand2tetris. One reason to do the mapping/allocation to fixed memory addresses at a later stage is that in more complex toolchains you may have several libraries being translated separately and linked together at a later point of time. In such scenarios it is impossible to know the absolute address at translation time.

Regarding your general concern about inefficiency, this can become an issue for the variables with indirect addressing (local, argument, this). For these variables it is possible to follow your approach and concatenate multiple A=A+1 to maintain the contents of D. In fact, for small indexes this is the most efficient approach. However, the generic case requires to use one of the internal registers R13-R15 which can be used by the VM translator to temporarily store the address. This is shorter and faster for high indexes and works in general for all indexes. A pop local 19 would for sure be better using one of the R13-R15 registers.