On Wed, Jul 15, 2009 at 13:51, Dragan<[email protected]> wrote: > > Hi, > > I am trying to compare the performance of java loops to clojure reduce > function. Noting special, Since I am just learning. > Java code is something like: > > [code] > long sum = 0; > for (int i = 1; i < 1000000; i++ ){ > sum = sum + i; > } > [/code] > > while in Clojure I used: > > [code] > (reduce + (range 1 i)) > [/code] > > Execution time for the Java version is 7 ms, while Clojure needs 60 - > 160 ms. > Now, that is expected, since Clojure runs in REPL.
Code run from the REPL won't run any slower (or faster) than code
that's compile ahead of time. Clojure compiles all code to java
classes before execution, regardless of how it is loaded.
> Next, I tried the gen-class of the Clojure, and called that Class from
> Java (so no REPL involved), but the code haven't speed up at all!
> Am I missing something or such 10x performance penalty is usual for
> such operations?
You're probably seeing the cost of boxing the numbers and of using
BigInteger to represent the sum. Being something of a newbie myself, I
tried to speed up your code:
(defn sum-of-range-1 [range-limit]
(reduce + (range 1 range-limit)))
When I ran (sum-of-range-1 1000000) one thousand times, it took 34.54
s on my machine
An explicit loop with some type hints is faster, though likely not as
fast as Java:
(defn sum-of-range-4 [range-limit]
(loop [i (int 1) s (long 0)]
(if (< i range-limit)
(recur (inc i) (+ s i))
s)))
This took 20.275s for the same scenario.
// Ben
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---
sum.clj
Description: Binary data
