Next: Trace Files and Disassembly
Up: General Efficiency Hints
Previous: Complex Argument Syntax
  Contents
  Index
Mapping and Iteration
efficiency of
One of the traditional Common Lisp programming styles is a highly applicative one,
involving the use of mapping functions and many lists to store intermediate
results. To compute the sum of the square-roots of a list of numbers, one
might say:
(apply #'+ (mapcar #'sqrt list-of-numbers))
This programming style is clear and elegant, but unfortunately results
in slow code. There are two reasons why:
- The creation of lists of intermediate results causes much
consing (see 5.12.2).
- Each level of application requires another scan down the list.
Thus, disregarding other effects, the above code would probably take
twice as long as a straightforward iterative version.
An example of an iterative version of the same code:
(do ((num list-of-numbers (cdr num))
(sum 0 (+ (sqrt (car num)) sum)))
((null num) sum))
See sections 5.3.1 and 5.4.1
for a discussion of the interactions of iteration constructs with type
inference and variable optimization. Also, section
5.6.4 discusses an applicative style of
iteration.
Next: Trace Files and Disassembly
Up: General Efficiency Hints
Previous: Complex Argument Syntax
  Contents
  Index
Peter Van Eynde
2000-02-08