引言自 https://clojure.org/reference/transducers#_creating_transducible_processes
转换过程必须封装由调用转换器返回的函数的引用
这些可能有状态且不安全
用于跨线程使用。
- 这是否意味着可以创建不安全的转换器以提高
性能?
- 核心的状态转换器可以编写不安全
以获得接近 loop
/recur
的性能?
clojure.core/drop
不安全实施的基准测试
(definterface IMutable
(get [])
(set [new-val]))
(deftype UnsynchronizedMutable [^:unsynchronized-mutable n]
IMutable
(get [_] n)
(set [_, nv] (set! n nv)))
(defn drop!
([n]
(fn [rf]
(let [nv (UnsynchronizedMutable. n)]
(fn
([] (rf))
([result] (rf result))
([result input]
(let [^long n (.get nv)]
(.set nv (dec n))
(if (pos? n)
result
(rf result input)))))))))
(comment
(criterium.core/quick-bench
(transduce (comp
(map inc)
(drop 1))
+ (range 1000)))
#_"Execution time mean : 39,455570 µs"
(criterium.core/quick-bench
(transduce (comp
(map inc)
(drop! 1))
+ (range 1000)))
#_"Execution time mean : 24,979885 µs")