为什么我的传感器功能比使用 - >>运算符慢?

den*_*631 5 reduce functional-programming clojure transducer

虽然从解决问题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"))
Run Code Online (Sandbox Code Playgroud)

Tay*_*ood 6

根据Criterium的说法,换能器版本似乎更快了:

(crit/quick-bench (string-compression-2 "aaabccdddd"))
             Execution time mean : 6.150477 µs
    Execution time std-deviation : 246.740784 ns
   Execution time lower quantile : 5.769961 µs ( 2.5%)
   Execution time upper quantile : 6.398563 µs (97.5%)
                   Overhead used : 1.620718 ns

(crit/quick-bench (string-compression-3 "aaabccdddd"))
             Execution time mean : 2.533919 µs
    Execution time std-deviation : 157.594154 ns
   Execution time lower quantile : 2.341610 µs ( 2.5%)
   Execution time upper quantile : 2.704182 µs (97.5%)
               Overhead used : 1.620718 ns
Run Code Online (Sandbox Code Playgroud)

正如coredump评论的那样,一个样本大小不足以说明一种方法通常比另一种方法更快.

  • 如果性能是您最关心的问题,那么您只需要进行基准测试(使用一系列输入)来查看哪种方法表现优异.我不会说_always_使用传感器; 它们在许多情况下具有性能优势,但它们也具有非性能相关的好处."这取决于" :) (2认同)
  • FWIW,[xforms](https://github.com/cgrand/xforms/)库有一个`net,cgrand.xforms.rfs/str`减少函数,它使用stringbuilder来避免这个问题. (2认同)