3.4 Using optimized constructs

3.4.3 Constant folding

The Compiler can perform an optimization called constant folding on a form that has no side effects and that can be evaluated repeatedly to produce values that areeql. During compilation, the form is evaluated and replaced by its value. Forms that can be constant folded include symbols defined by usingdefconstant, atoms other than symbols, lists whose car isquote, and constant numerical expressions.

The Compiler can use constant folding on each of the following expressions:

(+ 1 2)
(* 2.0 pi)
'(this is a constant list)
\#(a constant vector)
(aref \#(a b c) 1)
(car '(a b))
"Hi, I'm a string"
'(a b)

The Compiler does not use constant folding on the following expressions:

(list 'values 'of 'this 'expression 'are 'not 'eql)
(cons 'a 'b)
(make-array 10)
(* 0 (random-function-that-may-have-side-effects))

Nonnumerical expressions that allocate new storage are usually not folded because the values are noteql.

Note: You should never update structures created from constant forms because constant objects that appear in compiled code might be allocated by the loader in a read-only area in memory.

For example, the following function is incorrect:

(defun this-will-lose ()
  (let ((x \#(0 0 0)))
    (setf (aref x 0) 1)  ; Cannot update constants.

The following function is correct:

(defun this-will-win ()
  (let ((x (copy-seq \#(0 0 0))))
    (setf (aref x 0) 1)  

The Advanced User's Guide - 9 SEP 1996

Generated with Harlequin WebMaker