主要是介绍没有泛型的情况下,hashmap实现上的一些高效考虑
Go’s map is a hashmap
hash function
- The first is stability. The hash function must be stable. Given the same key, your hash function must return the same answer
- The second property is good distribution. Given two near identical keys, the result should be wildly different
In this case our hashmap has eight buckets (as this is the value that the Go implementation uses) and each bucket can hold up to eight entries each (again drawn from the Go implementation)
a hash map four properties
- You need a hash function for the key.
- You need an equality function to compare keys.
- You need to know the size of the key and,
- You need to know the size of the value because these affect the size of the bucket structure, which the compiler needs to know, as you walk or insert into that structure, how far to advance in memory.
java
boxing: boolean,
int,
short,
long,
byte,
char,
float, and
double to java.lang.Object
c++同java实现hashmap的优缺点
c++
- key和value的大小,在compile阶段就知道
- 可以进行inlineing
- 速度快
- 编译和代码上慢,要有不同的types
java
- 天然有泛型的含义,一切都是object
- 同样也是缺点,boxing等方式,会增大gc的概率
- Buckets are stored as linked lists, not sequential arrays
golang的实现
While we have the container/{list,heap}
packages which do use the empty interface, the runtime’s map implementation does not use interface{}
.
1 | v := m["key"] → runtime.mapaccess1(m, ”key", &v) |
实际上针对channel的操作?
1 | func mapaccess1(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer |
在mapaccess中,指明maptype,不同于c++部分针对所有的map有不同的实现,golang部分,在compile阶段生成maptype字段
1 | type maptype struct { |
mapaccess的功能如下:
1 | // mapaccess1 returns a pointer to h[key]. Never returns nil, instead |