有人可以告诉我如何在Common Lisp中内联函数吗? 我有很多小的函数,它们总是被调用,因此最好节省这些函数调用的成本。
例如,您如何在“调用者”功能内插入“独立”功能?
(defun standalone ()
(* 2 5))
(defun caller ()
(standalone))
答案 0 :(得分:3)
(declaim (inline standalone))
(defun standalone ()
(* 2 5))
(defun caller ()
(standalone))
文档为here。
(但是请记住,定义一个始终返回数字文字10的函数没有多大意义...)
答案 1 :(得分:3)
请参阅食谱: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)))
答案 2 :(得分:1)
诸如Allegro CL编译器ignore inline declarations之类的某些实现。
由"details": {
创建的 Compiler macros(不同于define-compiler-macro
!)也可以用于内联代码。