performance - 使用 Clojure 宏内联函数

标签 performance compiler-construction macros clojure

出于对其他任何事情的好奇(但期望它偶尔会成为性能调整的有用技巧),是否可以使用 Clojure 宏来“内联”现有函数?

即我希望能够执行以下操作:

(defn my-function [a b] (+ a b))

(defn add-3-numbers [a b c] 
  (inline (my-function 
    a 
    (inline (my-function 
      b 
      c)))))

并让它(在编译时)产生与我自己内联添加的完全相同的功能,例如:
(defn add-3-numbers [a b c] 
  (+ a (+ b c)))

最佳答案

如果您不知道,您可以使用 definline 定义内联函数

(doc definline)
-------------------------
clojure.core/definline
([name & decl])
Macro
  Experimental - like defmacro, except defines a named function whose
  body is the expansion, calls to which may be expanded inline as if
  it were a macro. Cannot be used with variadic (&) args.
nil

还要检查来源,
(source definline)
-------------------------
(defmacro definline
  [name & decl]
  (let [[pre-args [args expr]] (split-with (comp not vector?) decl)]
    `(do
       (defn ~name ~@pre-args ~args ~(apply (eval (list `fn args expr)) args))
       (alter-meta! (var ~name) assoc :inline (fn ~name ~args ~expr))
       (var ~name))))
definline简单定义一个 var带有元数据 {:inline (fn definition)} .因此,尽管它不完全符合您的要求,但您可以使用新的元数据重新绑定(bind) var 以获得内联行为。

关于performance - 使用 Clojure 宏内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4477759/

相关文章:

c# - 编辑和调试时 Visual Studio 2015 变慢

c++ - 声明空堆栈的最有效方法是什么?

python - 高效地与请求异步下载文件

c++ - 第一次机会异常 - 长时间在内存位置?

python - python 的注释(例如数据类)可以扩展到它生成的代码中吗?

MACRO 可以定义为一个数组吗?

使用具有复杂检查的局部变量的多个 && 的 C# 性能 - 编码风格与性能

c# - 如何区分 Null 或 Empty ?根据什么标准处理 Null 和 Empty?

c# - 为什么 C# 编译器区分这两种情况?

c++ - 特定的 C++ 宏