On Wed, Dec 22, 2010 at 1:19 PM, Rayne <[email protected]> wrote:
> chouser wrote a solution earlier. I and a buddy modified it (a very
> little) bit and managed to get it pretty blazing:
>
> ra...@ubuntu:~$ cake run ~/challenge.clj
> Chars outputted: 460
> Time (in nanoseconds): 5768.677
>
> Here is the function:
>
> (defn count-num-chars [^String s]
> (let [len (.length s)
> space (int 32)]
> (loop [i (int 0), c (int 0)]
> (if (< i len)
> (recur
> (inc i)
> (if (== (.codePointAt s i) space)
> c
> (unchecked-inc c)))
> c))))
I get about 6000ns with this also. It looks like one bit of Clojure in
need of improvement is the handling of the = operator: if at compile
time it's known that either side is a primitive or a character
constant, it really ought to boil down to a Java == operator, but
apparently it doesn't, and JIT and branch prediction don't suffice to
render the difference moot.
Also, == doesn't seem to work with characters -- ClassCastException
java.lang.Character can't be cast to java.lang.Number. This with
\space or (char \space) on the right hand side and (.charAt s i) on
the left. The odd thing is this suggests == isn't a raw Java ==
operator call but rather a method call of Number, likely .equals.
Which shouldn't be particularly fast.
Now, identical? IS supposed to be Java's == operator but for
(defn count-num-chars [^String s]
(let [l (int (.length s)) c (char \space)]
(loop [i (int 0) acc (int 0)]
(if (< i l)
(recur (unchecked-inc i) (if (identical? (.charAt s i) c) acc
(unchecked-inc acc)))
acc))))
I get 9000ns, about two-thirds the speed I get using == and .codePointAt.
Something interesting is going on among =, ==, and identical? here,
but I'm not 100% sure what. Perhaps identical? is not managing to have
its function call overhead JITted away, while the Clojure compiler
treats the operators specially; in theory it *should* be fastest.
--
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