I have a piece of code, and I'd like to see how fast it can be.
(defn count-num-chars [^String s]
(loop [s s acc 0]
(if (seq s)
(recur (rest s) (if (= (first s) \space) acc (inc acc)))
acc)))
This is the fastest I've been able to get it. The function is very
simple. It takes a string and counts the number of non-space
characters inside of that string.
I've been testing this code against a 460 non-space character string.
Here is the entire source, benchmarking and all:
(def s (apply str (repeat 20 "This is a really long string")))
(defn count-num-chars [^String s]
(loop [s s acc 0]
(if (seq s)
(recur (rest s) (if (= (first s) \space) acc (inc acc)))
acc)))
(println "Chars outputted:" (count-num-chars s))
(let [before (System/nanoTime)]
(dotimes [_ 1000]
(count-num-chars s))
(let [after (System/nanoTime)]
(println "Time (in nanoseconds):" (/ (- after before) 1000.0))))
Running it gives me around 137343.295 nanoseconds. I've seen some Java
algorithms that could run at just under 3000 nanoseconds.
Hide your children and hide your women; I want to see the direst,
nastiest, rawest, fastest possible implementation of this function.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en