Hi,

On Feb 22, 2010, at 1:43 AM, Meikel Brandmeyer wrote:

> Hi,
> 
> On Feb 22, 12:18 am, Johnny Kwan <johnny.c.k...@gmail.com> wrote:
>> I'm really new to Clojure, but I'm under the impression that reduce would
>> be better than apply, since I assume that apply would reify the entire
>> sequence at once, whereas reduce would consume the sequence one by one.
>> Could someone more familiar with the implementation weigh in on this?
> 
> apply is lazy.
> 
> user=> (defn test-apply [& xs] (prn (take 10 xs)))
> #'user/test-apply
> user=> (apply test-apply (iterate inc 0))
> (0 1 2 3 4 5 6 7 8 9)
> nil
> 
> Sincerely
> Meikel

Hmm, I don't know enough about how well the Java AOT compiler and JIT compiler 
optimizes this in general.  But just because apply is lazy doesn't mean that 
when apply is finally realized, the entire sequence doesn't have to be reified 
to call the function.  Reading through the implementation of .applyTo and 
.applyToHelper in clojure.lang.AFn makes this clear.

Here's a concrete example:

(time (reduce + (range 1 10000000))) ; 4.5 secs on my Macbook Air
(time (apply + (range 1 10000000))) ; OutOfMemory error

Whichever is faster depends on the size of the argument list, since apply is 
called once with the concrete arglist, and reduce is called many times with 
just 2 args.  However, apply certainly seems to try to shove the entire 
sequence into an array, at least on the OSX Snow Leopard JVM.

Thanks,
Johnny

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