Hi,

> 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)))

I get an average of 46928 for this.


But for the straightforward option of reduce:

(defn count-num-chars3 [^String s]
  (reduce (fn [acc c] (if (= c \space) acc (inc acc))) 0 s))

I get an average of 27424.  Cool!  So writing it the nicest way, is
also faster.


I tend to avoid spamming .charAt even in Java for things like this,
and often find converting to an array first to be faster, like this:

(defn count-num-chars4 [^String s]
  (let [as (.toCharArray s)]
    (areduce as idx acc 0 (if (= (int (aget as idx)) (int \space)) acc (inc 
acc)))))

I get an average of 3631.

(needed to cast the char to int there, else clojure seems to hit
reflection problems)

-- 
Dave

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to