Capacity in maps

5,444 views
Skip to first unread message

Archos

unread,
Apr 24, 2012, 9:21:40 AM4/24/12
to golang-nuts
Which is the goal to have an optional capacity as argument in maps? If
can be set more elements than given by the capacity

http://play.golang.org/p/Pvd38xW2WT

Archos

unread,
Apr 24, 2012, 9:24:35 AM4/24/12
to golang-nuts
And I know about: "The initial capacity does not bound its size: maps
grow to accommodate the number of items stored in them..."

But I don't find an use to have it

mjarco

unread,
Apr 24, 2012, 9:25:13 AM4/24/12
to golan...@googlegroups.com
The goal is to not resize map to often. If you know that you will store 10000 entries in map, it's better to allocate map with such (or greater) capacity.

Archos

unread,
Apr 24, 2012, 9:29:34 AM4/24/12
to golang-nuts

On Apr 24, 2:25 pm, mjarco <mja...@gmail.com> wrote:
> The goal is to not resize map to often. If you know that you will store
> 10000 entries in map, it's better to allocate map with such (or greater)
> capacity.
Ok. And why cann't be got the initial capacity given in the map? (If
any)
The function cap() is not valid in maps.

Canopée

unread,
Apr 24, 2012, 9:29:58 AM4/24/12
to golan...@googlegroups.com
Speaking of that, is there somewhere a description of Go's
implementation of map ?

The link between capacity and consequences is very clear when you're
speaking of the canonical implementation of a hash table but a quick
look at the code made me think that Go's map is more complex than that.
What kind of map is it ?

mjarco

unread,
Apr 24, 2012, 9:38:13 AM4/24/12
to golan...@googlegroups.com
AFAIK maps are hash tables, but I haven't look into sources that's my impression after I http://research.swtch.com/randhash lecture

Ian Lance Taylor

unread,
Apr 24, 2012, 10:59:29 AM4/24/12
to Archos, golang-nuts
Archos <raul...@sent.com> writes:

> Ok. And why cann't be got the initial capacity given in the map? (If
> any)
> The function cap() is not valid in maps.

It's hard to see why that would be an interesting number. The capacity
is an important number for a slice. But we don't want to constrain the
implementation of the map datatype by defining exactly what the capacity
of a map is. And if we don't define the capacity, then the cap function
is not useful.

It might be better to think of the optional second argument to make when
making a map not as the capacity, but as a hint as to the number of
elements expected to go into the map. And you can use len to get the
number of elements that are actually in the map.

Ian

Reply all
Reply to author
Forward
0 new messages