来自 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")