by pjstirling » Tue Nov 12, 2013 6:35 am
Constant folding is a simple technique for increasing the execution speed of code where the compiler uses the fact that a particular function when invoked with particular arguments will always return the same result. When the compiler can work out that result at compile time it can simply put the constant value into the variable at run-time without doing any calculations at run-time.
Calculating sin(x) takes quite a lot of calculations for a computer, but for any constant value of x, it will have a constant result. An example would be (SIN (/ PI 2)), which always has the result 1.0d0. A compiler can use this fact to replace (SIN (/ PI 2)) with 1.0d0 and save these 'wasted' calculations. Things are slightly more complicated in common-lisp though, because although you do want to constant-fold SIN when possible, you also need to be able to call it at run time (in particular you might want to (MAPCAR #'SIN ...), so it can't be a pure macro, or function. The third way in common-lisp is compiler-macros, rather than using DEFMACRO you would use normal DEFUN, which gets used for run-time calculations, and a compiler-macro (DEFINE-COMPILER-MACRO), which can be used for constant-folding, which means that SIN becomes both a macro and a function.
As another example, I have an html generation library that aggressively folds the string constants used in the FORMAT calls which I need to get around to putting on github