Guys, thanks very much for the fast responses. Of course, this is an unscientific and totally ad-hock benchmark. I am just *learning* Clojure and functional programming and I wanted to get some feeling of how fast Clojure is comparing to java when equivalent idioms are used . Of course, loop and reduce are not really equivalent, but I would use them for similar tasks, that 's why I wanted to compare them (instead for example loop vs loop). That's why it's great to hear those "duh" tips :)
On Jul 15, 5:39 pm, B Smith-Mannschott <bsmith.o...@gmail.com> wrote: > On Wed, Jul 15, 2009 at 13:51, Dragan<draga...@gmail.com> 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 > > sum.clj > < 1KViewDownload --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---