While solving problem from Hackkerank (https://www.hackerrank.com/challenges/string-compression/problem) I've written 2 implementations with and without transducers.
I was expecting the transducer implementation to be faster, than the function chaining operator ->>
. Unfortunately, according to my mini-benchmark the chaining operator was outperforming the transducer by 2.5 times.
I was thinking, that I should use transducers wherever possible. Or didn't I understand the concept of transducers correctly?
Time:
"Elapsed time: 0.844459 msecs"
"Elapsed time: 2.697836 msecs"
Code:
(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"))