It's not dependent on whether it's a literal but on the size of the map, 8
key-value pairs is the threshold.

This results in a PersistentHashMap
(class {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9})  =>
clojure.lang.PersistentHashMap

This gets you a PersistentArrayMap
(class {1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8})  => clojure.lang.PersistentHashMap

You can see where this happens in the source here:
https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentArrayMap.java#L115

HASHTABLE_THRESHOLD is a constant set to 16, 8 keys and 8 values. So when
you assoc onto an arraymap with 8 key-value pairs it returns a hashmap.

The reason for this, as far as I understand it, is that with small hashmaps
it's more efficient to do simple copy-on-write. In other words when you
assoc onto it, it copies the entire map, adds the new key-value pair to the
copy, and then returns the copy. With larger hashmaps, it becomes more
useful to do use a more complicated tree structure which uses structural
sharing so that assoc doesn't copy the entire map. Copying a small 5
element map isn't a big deal, but copying one with several thousand
elements is.

On Fri, Aug 10, 2012 at 5:43 PM, Hussein B. <hubaghd...@gmail.com> wrote:

> Hi,
> Why Clojure map literal creates an instance of array map but not hash map?
> What are the advantages of array map over hash map?
> Thanks.
>
> --
> 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

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