On Fri, Mar 6, 2009 at 7:00 AM, Chouser <[email protected]> wrote:
>
> On Fri, Mar 6, 2009 at 7:55 AM, Mark Volkmann <[email protected]>
> wrote:
>>
>> When working on a list, both cons and conj add to the front. In my
>> tests, cons is considerably faster than conj. I'm trying to figure out
>> why.
>
> In my testing they are the same speed.
Here's my code that seems to show that cons is faster than conj for
both lists and vectors. Am I doing something suspect that is skewing
my results?
(def size 10000)
(defn build-coll
"prints the time required to change the contents of a collection
to the result of a given function n times
where values from 0 to n-1 are passed to the function"
[coll a-fn size]
(let [an-atom (atom coll)]
(time
(dotimes [i size]
(reset! an-atom (a-fn @an-atom i))))
;(println @an-atom)
))
(println "\nconj list")
; Adds to front.
(build-coll '() (fn [coll i] (conj coll i)) size)
(println "\ncons list")
; Adds to front.
(build-coll '() (fn [coll i] (cons i coll)) size)
(println "\nconj vector")
; Adds to back.
(build-coll [] (fn [coll i] (conj coll i)) size)
(println "\ncons vector")
; Adds to front.
(build-coll [] (fn [coll i] (cons i coll)) size)
>> Here's the implementation of conj.
>>
>> (def
>> #^{:arglists '([coll x] [coll x & xs])
>> :doc "conj[oin]. Returns a new collection with the xs
>> 'added'. (conj nil item) returns (item). The 'addition' may
>> happen at different 'places' depending on the concrete type."}
>> conj (fn conj
>> ([coll x] (. clojure.lang.RT (conj coll x)))
>> ([coll x & xs]
>> (if xs
>> (recur (conj coll x) (first xs) (next xs))
>> (conj coll x)))))
>>
>> The line for the parameter list [coll x] seems to call itself
>> recursively with the exact same arguments. How does that ever
>> terminate?
>
> You're probably getting confused by the old-style Java interop syntax.
>
> (. clojure.lang.RT (conj coll x))
>
> is the same as:
>
> (clojure.lang.RT/conj coll x)
Ah ... you're right! I haven't looked at the old style in a while. It
seems weird that it can break apart (conj coll x) to get what you show
above before evaluating it. I much prefer the new style.
--
R. Mark Volkmann
Object Computing, Inc.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
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
-~----------~----~----~----~------~----~------~--~---