在解决 Hackkerank ( https://www.hackerrank.com/challenges/string-compression/problem ) 的问题时,我编写了 2 个带有和不带有传感器的实现。
我期望传感器实现比函数链接运算符更快->>
。不幸的是,根据我的迷你基准,链接运算符的性能比传感器高 2.5 倍。
我在想,我应该尽可能使用传感器。还是我没有正确理解传感器的概念?
时间:
“经过时间:0.844459 毫秒”
“经过时间:2.697836 毫秒”
代码:
(defn string-compression-2
[s]
(->> s
(partition-by identity)
(mapcat #(if (> (count %) 1)
(list (first %) (count %))
(list (first %))))
(apply str)))
(def xform-str-compr
(comp (partition-by identity)
(mapcat #(if (> (count %) 1)
(list (first %) (count %))
(list (first %))))))
(defn string-compression-3
[s]
(transduce xform-str-compr str s))
(time (string-compression-2 "aaabccdddd"))
(time (string-compression-3 "aaabccdddd"))