Re:Google Closure: How not to write Javascript
by qeorge on Thursday November 12, 2009 @11:13AM
(#938005)
Brilliant, thank you for the explanation and the Wikipedia link. I'm going to stop by the library this weekend to see if they have any books on compiler design, do you have any recommendations there?
Thanks again, its great to learn something new.
Re:Google Closure: How not to write Javascript
by nostrademons on Thursday November 12, 2009 @01:25PM
(#938377)
The classic is the "Dragon Book":
http://www.amazon.com/Compilers-Principles-Techniques-Alfred...
I'm also partial to Appel's "Modern Compiler Implementation in ML", because it goes into more detail about techniques for compiling functional languages:
http://www.amazon.com/Modern-Compiler-Implementation-Andrew-...
This is a specific example of dataflow analysis, which is a fascinating area of compiler design. Usually you'll use something like a use-def chain to figure out all the points where a variable might've been defined. If all of those are outside of the loop, then the computation itself may be moved outside of the loop too, and the loop just refers to the temporary that's the result. I'd encourage you to pick up a book on compiler design if you're interested; here's the Wikipedia article:
http://en.wikipedia.org/wiki/Use-define_chain
This explicitly doesn't apply to "smart" containers like Vectors, which automatically resize themselves. If you were to inline these methods, you'd see that the internal buffer pointer may change inside the loop (assuming that you call functions that mutate the object; if you don't, and the language has a notion of const-correctness, a sufficiently smart compiler could probably optimize them too), and so the compiler can't move any code outside. Same with strlen; its return value depends upon the contents of the memory buffer pointed to, so unless the compiler can prove that that memory buffer never changes (hard; any function may reach in through a pointer and set a character to null), it can't optimize the call away.