Here are some tips for making compiled code run fast(er):
whileloops to traverse lists, use
mapcor tail recursion.
For example you might code a function to scan a list using iteration
(defun scan-list (lst elt) "Search the LST for an element similar to ELT. Return it if one is found." (catch 'return (while (consp lst) (when (equal (car lst) elt) (throw 'return elt)) (setq lst (cdr lst)))))
As well as obscuring what is actually happening, this will probably be fairly slow to execute. A more elegant solution is to use tail-recursion:
(defun scan-list (lst elt) (if (equal (car lst) elt) elt (scan-list (cdr lst) elt)))
An alternative idiom is to map an anonymous function over the list
(defun scan-list (lst elt) (catch 'return (mapc (lambda (x) (when (equal x elt) (throw 'return elt))) lst) nil))
In fact, the compiler knows that calls to
mapc with a constant
lambda expression can be open-coded, so it will code the list traversal
directly using the virtual machine stack.
However, in most cases the execution time differences are likely to negligible.
assoc, etc… can be used to search lists. Since these are primitives written in C they will probably execute several times faster than an equivalent Lisp function.
So the above
scan-list example can again be rewritten, this time
(defun scan-list (lst elt) (car (member elt lst)))
condstatements), so use whichever is the easiest to understand.
(logor (lsh 1 6) x) → (logor 32 x)
It must be stressed that in some cases constants may not be
suitable; they may drastically increase the size of the compiled
program (when the constants are ‘big’ objects, i.e. long lists) or even
introduce subtle bugs (since two references to the same constant may
eq whereas two references to the same variable are always
then the form is compiled. Otherwise it is just written to the output file in its uncompiled state.
If your program contains a lot of top-level forms which you know will
not be compiled automatically, consider putting them in a
block to make the compiler coalesce them into one byte-code form.