声明函数会导致 Clojure 中出现任何性能问题吗?
Does declare function cause any performance problems in Clojure?
如您所知,如果我们想使用一个函数而不事先声明它,我们需要使用 declare
函数,所以我的问题是使用 declare
函数会导致任何性能问题吗?
Clojure 有 single pass compilation
所以我假设它必须在那里做某种权衡?
Clojure 没有单程编译器,只是编译单元不是文件。有关参考,请参阅 this thread。 declare 所做的只是在当前命名空间中定义一个没有值的 var,以便以后可以重新定义它。因此,对普通变量没有性能影响。
但是,如果您开始考虑优化您的代码,您可能会开始添加诸如定义某些代码的内联版本之类的内容,在声明调用和内联函数定义之间编译的任何内容都不会该调用内联。
(declare some-func)
(defn other-func [] (some-func))
(defn some-func
{:inline (fn [] "test-inline")}
[] "test")
(other-func) ;;=> "test"
(defn other-func [] (some-func))
(other-func) ;;=> "test-inline"
我按如下方式尝试了 Criterium:
(ns speed-test.core
(:require [criterium.core :as crit]))
(declare this)
(defn bench-this [] (crit/bench (this)))
(defn this [])
(defn that [])
(defn bench-that [] (crit/bench (that)))
我发现 bench-this
和 bench-that
之间没有显着差异。由于这两种情况下的平均执行时间都是 7 - 8 ns,我感觉我们正在测量 HotSpot 无法放置的虚无的幽灵。
如您所知,如果我们想使用一个函数而不事先声明它,我们需要使用 declare
函数,所以我的问题是使用 declare
函数会导致任何性能问题吗?
Clojure 有 single pass compilation
所以我假设它必须在那里做某种权衡?
Clojure 没有单程编译器,只是编译单元不是文件。有关参考,请参阅 this thread。 declare 所做的只是在当前命名空间中定义一个没有值的 var,以便以后可以重新定义它。因此,对普通变量没有性能影响。
但是,如果您开始考虑优化您的代码,您可能会开始添加诸如定义某些代码的内联版本之类的内容,在声明调用和内联函数定义之间编译的任何内容都不会该调用内联。
(declare some-func)
(defn other-func [] (some-func))
(defn some-func
{:inline (fn [] "test-inline")}
[] "test")
(other-func) ;;=> "test"
(defn other-func [] (some-func))
(other-func) ;;=> "test-inline"
我按如下方式尝试了 Criterium:
(ns speed-test.core
(:require [criterium.core :as crit]))
(declare this)
(defn bench-this [] (crit/bench (this)))
(defn this [])
(defn that [])
(defn bench-that [] (crit/bench (that)))
我发现 bench-this
和 bench-that
之间没有显着差异。由于这两种情况下的平均执行时间都是 7 - 8 ns,我感觉我们正在测量 HotSpot 无法放置的虚无的幽灵。