如何在 Common Lisp 中内联函数

How to inline functions in Common Lisp

有人可以告诉我如何在 Common Lisp 中内联一个函数吗? 我有很多小函数一直在调用,所以最好节省这些函数调用的成本。

例如,如何将 "standalone" 函数内联到 "caller" 函数中?

(defun standalone ()
 (* 2 5))

(defun caller ()
 (standalone))
(declaim (inline standalone))

(defun standalone ()
 (* 2 5))

(defun caller ()
 (standalone))

文档是 here

(但请记住,定义一个 总是 returns 数字文字 10 的函数没有多大意义...)

查看食谱:https://lispcookbook.github.io/cl-cookbook/performance.html#code-inline

如果编译器支持,内联声明将函数调用替换为函数体。它将节省函数调用的成本,但可能会增加代码大小。使用内联的最佳情况可能是那些小但经常使用的函数。以下片段展示了如何鼓励和禁止内联代码。

;; The globally defined function DISPATCH should be open-coded,
;; if the implementation supports inlining, unless a NOTINLINE 
;; declaration overrides this effect.
(declaim (inline dispatch))
(defun dispatch (x) (funcall (get (car x) 'dispatch) x))

;; Here is an example where inlining would be encouraged.
;; Because function DISPATCH was defined as INLINE, the code 
;; inlining will be encouraged by default.
(defun use-dispatch-inline-by-default () 
  (dispatch (read-command)))

;; Here is an example where inlining would be prohibited.
;; The NOTINLINE here only affects this function.
(defun use-dispatch-with-declare-notinline  ()
  (declare (notinline dispatch))
  (dispatch (read-command)))

;; Here is an example where inlining would be prohibited.
;; The NOTINLINE here affects all following code.
(declaim (notinline dispatch))
(defun use-dispatch-with-declaim-noinline () 
  (dispatch (read-command)))

;; Inlining would be encouraged becuase you specified it.
;; The INLINE here only affects this function.
(defun use-dispatch-with-inline () 
  (declare (inline dispatch))
  (dispatch (read-command)))

一些实现,例如 Allegro CL 编译器 ignore inline declarations

Compiler macrosdefine-compiler-macro 创建(不同于 defmacro!)也可以用来代替内联代码。