r/Clojure • • Mar 16 '26

Let's optimize 'str'!

Post image
(defn my-str
  "With no args, returns the empty string. With one arg x, returns
  x.toString().  (str nil) returns the empty string. With more than
  one arg, returns the concatenation of the str values of the args."
  (^String [] "")
  (^String [^Object x]
   (if (nil? x) "" (. x (toString))))
  (^String [^Object x & ys]
   (let [sb (StringBuilder. (if-not (nil? x) (.toString ^Object x) ""))]
     (loop [ys (seq ys)]
       (when-not (nil? ys)
         (let [x (.first ys)]
           (when-not (nil? x)
             (.append sb (.toString ^Object x)))
           (recur (.next ys)))))
     (.toString sb))))

; ==== Benchmarks ====

(let [xs (vec (range 1000))]
    (criterium/bench
      (dotimes [_ 10000]
        (apply str xs))))
Evaluation count : 240 in 60 samples of 4 calls.
             Execution time mean : 315.920876 ms
    Execution time std-deviation : 3.017554 ms
   Execution time lower quantile : 314.071842 ms ( 2.5%)
   Execution time upper quantile : 323.751886 ms (97.5%)
                   Overhead used : 7.818691 ns
...
=> nil
(let [xs (vec (range 1000))]
    (criterium/bench
      (dotimes [_ 10000]
        (apply my-str xs))))
Evaluation count : 300 in 60 samples of 5 calls.
             Execution time mean : 229.861009 ms
    Execution time std-deviation : 2.092937 ms
   Execution time lower quantile : 228.744368 ms ( 2.5%)
   Execution time upper quantile : 233.181852 ms (97.5%)
                   Overhead used : 7.818691 ns
...
=> nil

Mostly for fun. What is your opinion about core functions performance?

40 Upvotes

15 comments sorted by

View all comments

Show parent comment

3

u/joinr Mar 16 '26

cool.

build-string was meant to be a helper macro for emitting the function bodies for make-string. make-string is the 1:1 replacement for clojure.core/str, since it's a function and can be passed around as such (build-string can't be used in apply, map, reduce, etc since it's a macro).

Still, the smarter sb-builder capacity stuff can maybe help make function bodies for make-string faster as well.

Though, if you know your inputs are all string literals or atomic values that have a direct string coercion (e.g. not forms to be eval'd), you can also just do it all at compile time:

(defmacro compile-str [& xs]
    `~(apply str xs))

(c/quick-bench
 (compile-str "Lorem" "Ipsum" "is" "simply" "dummy" "text"
              "of" "the" "printing" "and" "typesetting" "industry."))

Execution time mean : 3.485020 ns

We actually get a little more performance (15%) out of make-string if we make simple-str a helper macro too and assumably avoid the function call:

(defmacro simple-str [x]
  (let [x (with-meta x {:tag 'Object})]
    `(if (nil? ~x)
       ""
       (.toString  ~x))))