M
Michael Wojcik
Scott said:Have you? I guess for languages like C/C++ or Java, or other
languages meant for heavy-weight lifting, this makes a good deal of
sense.
A standard peephole algebraic-simplification optimization, often
implemented even in toy compilers. There's a short discussion in the
"dragon book"[1] (section 9.10), and something similar should be in
any general text on compiler design.
I've never run across it before.
Really? Have you worked on compilers? (That's an honest question -
it's not like every good programmer has had occasion to write a compiler.)
Have you seen it for dynamic
languages? I imagine "eval" might erect barriers to many
optimizations that might otherwise be possible.
To some optimizations, yes, but typically not to single-statement and
peephole ones. Those are applied to the parse tree, so they happen
after any manipulation of the statement in question has occurred.
So, for example, if the source contains:
var foo = bar * 1;
there's no reason why the ES interpreter can't eliminate the
multiplication after parsing that statement - no eval is going to
affect the tree after it's been parsed. And similarly, if the code
contains:
var baz = "bar";
var foo = eval(baz + " * 1");
the string concatenation will happen first, then the string "bar * 1"
will be parsed (by eval), and optimizations can then be performed on
that parse tree. Nothing can change the string once it's passed to
eval - even in some future multithreaded ES implementation - so the
dynamic features of the language don't impede optimization at that point.
Where dynamic languages interfere with optimization is in larger
transformations. For example, inlining short functions is complicated
if those functions can be redefined at runtime.
There's a lot of literature on optimizing the LISP and ML language
families. I've seen some fairly dramatic optimization transformations
for Scheme (a LISP variant with first-order functions), for example,
including a general translation (ie, one proven to be correct for any
program) that converts all recursion into iteration.
[1] Aho, Sethi, Ullman. _Compilers: Principles, Techniques, and
Tools_. 1986. For a long time the standard textbook for
introduction-to-compilers classes in the US; called the "dragon book"
after its cover illustration.