Go语言map和slice的内存管理

379 阅读5分钟

1. 前言

  Go语言传参既支持传值,也支持传引用。基础类型的传递比较清晰,本文记录下传递map和slice的原理。

2. 初始化和赋值

2.1 使用方法

  map和slice类型都是通过make方法和new方法来初始化。使用make初始化时,会同时分配空间,使用new初始化时,不会分配空间,指向的是一个nil。   make方法的说明:map是不需要传入长度length的,slice可以接受两个长度参数,初始化的长度和容量。

// The make built-in function allocates and initializes an object of type
// slice, map, or chan (only). Like new, the first argument is a type, not a
// value. Unlike new, make's return type is the same as the type of its
// argument, not a pointer to it. The specification of the result depends on
// the type:
//	Slice: The size specifies the length. The capacity of the slice is
//	equal to its length. A second integer argument may be provided to
//	specify a different capacity; it must be no smaller than the
//	length. For example, make([]int, 0, 10) allocates an underlying array
//	of size 10 and returns a slice of length 0 and capacity 10 that is
//	backed by this underlying array.
//	Map: An empty map is allocated with enough space to hold the
//	specified number of elements. The size may be omitted, in which case
//	a small starting size is allocated.
//	Channel: The channel's buffer is initialized with the specified
//	buffer capacity. If zero, or the size is omitted, the channel is
//	unbuffered.
func make(t Type, size ...IntegerType) Type

  new出来的map不能赋值:

package main

import "fmt"

func main() {
	mapValue1 := make(map[int64]int64)
	mapValue2 := new(map[int64]int64)

	mapValue1[1] = 1
	(*mapValue2)[2] = 2

	fmt.Println(mapValue1)
	fmt.Println(*mapValue2)
}

  运行时会报错:panic: assignment to entry in nil map
  new出来的slice可以赋值(append)操作:

package main

import "fmt"

func main() {
	sliceValue1 := make([]int64, 0)
	sliceValue2 := new([]int64)

	sliceValue1 = append(sliceValue1, 100)
	*sliceValue2 = append(*sliceValue2, 200)

	fmt.Println(sliceValue1)
	fmt.Println(*sliceValue2)
}

  可以打印出信息。

2.2 内存分配

  map初始化就是返回一个hmap的结构体地址(可以理解为一个指针,指向了这个分配的结构体),具体的字段如下,任何语言的数组(php)或者map(java)里面都涉及到复杂的hash,就不在此详述。make时就会返回一个hmap结构体指针。
  map赋值时,需要先根据key找到那个对应的地址,然后对这个地址赋上对应的值。

// map的结构体
// A header for a Go map.
type hmap struct {
	// Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go.
	// Make sure this stays in sync with the compiler's definition.
	count     int // # live cells == size of map.  Must be first (used by len() builtin)
	flags     uint8
	B         uint8  // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
	noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
	hash0     uint32 // hash seed

	buckets    unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
	oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
	nevacuate  uintptr        // progress counter for evacuation (buckets less than this have been evacuated)

	extra *mapextra // optional fields
}

// make方法
func makemap_small() *hmap {
	h := new(hmap)
	h.hash0 = fastrand()
	return h
}

// 赋值方法
func mapassign_fast64(t *maptype, h *hmap, key uint64) unsafe.Pointer {
}

  slice初始化时会分配3*8=24bytes,分别保存着array,len,cap。array等于heap区返回的地址,在append时如果cap不够了,会自动增加cap。进行整个内存的copy,看起来效率会很低。

// slice结构体
type slice struct {
	array unsafe.Pointer
	len   int
	cap   int
}

// 分配
func makeslice(et *_type, len, cap int) unsafe.Pointer {}

// 扩大slice的cap
func growslice(et *_type, old slice, cap int) slice {}

3. 参数传递


  传递一个map变量时,实际上是传递了上面提到的分配hmap结构体的地址,可以理解为传递了引用。通过打印结果也可以反应这个机制。
package main

import "fmt"

func main() {
	mapValue1 := make(map[int64]int64)
	mapValue1[1] = 2

	mapValue2 := mapValue1
	mapValue2[3] = 4

	fmt.Println(mapValue1)
	fmt.Println(mapValue2)
}

// 打印信息
map[1:1 2:2]
map[1:1 2:2]

  传递一个slice变量时,实际上是复制了24bytes,通过汇编代码和打印信息,都可以验证。

package main

import "fmt"

func main() {
	sliceValue1 := make([]int64, 0, 10)
	sliceValue1 = append(sliceValue1, 100)

	sliceValue2 := sliceValue1
	sliceValue2 = append(sliceValue2, 200)

	fmt.Println(sliceValue1)
	fmt.Println(sliceValue2)
}

// 打印信息
[100]
[100 200]

// 汇编代码
  main.go:6		0x1099596		48890424		MOVQ AX, 0(SP)
  main.go:6		0x109959a		48c744240800000000	MOVQ $0x0, 0x8(SP)
  main.go:6		0x10995a3		48c74424100a000000	MOVQ $0xa, 0x10(SP)
  main.go:6		0x10995ac		e88f36faff		CALL runtime.makeslice(SB)
  main.go:6		0x10995b1		488b442418		MOVQ 0x18(SP), AX
  main.go:6		0x10995b6		4889442450		MOVQ AX, 0x50(SP)
  main.go:6		0x10995bb		48c744245800000000	MOVQ $0x0, 0x58(SP)
  main.go:6		0x10995c4		48c74424600a000000	MOVQ $0xa, 0x60(SP)
  main.go:7		0x10995cd		eb00			JMP 0x10995cf
  main.go:7		0x10995cf		48c70064000000		MOVQ $0x64, 0(AX)
  main.go:7		0x10995d6		4889442450		MOVQ AX, 0x50(SP)
  main.go:7		0x10995db		48c744245801000000	MOVQ $0x1, 0x58(SP)
  main.go:7		0x10995e4		48c74424600a000000	MOVQ $0xa, 0x60(SP)

  一个有趣的例子,可以加深slice传递的理解。sliceValue1和sliceValue2是两个不同的slice结构体,但是具体的值指向的地址是同一个空间,空间里面有2个值,100和200,但是sliceValue1的len为1,所以只会打印出100。sliceValue3等于&sliceValue1,此时sliceValue3只占用了8bytes,指向sliceValue1的地址,如果对sliceValue3进行append操作,sliceValue1结构体的len会发生变化,同时值空间指向的值也会发生变化,导致第二个值变成了300,从而影响了sliceValue2的值。

package main

import "fmt"

func main() {
	sliceValue1 := make([]int64, 0, 10)
	sliceValue1 = append(sliceValue1, 100)

	sliceValue2 := sliceValue1
	sliceValue2 = append(sliceValue2, 200)

	sliceValue3 := &sliceValue1
	*sliceValue3 = append(*sliceValue3, 300)

	fmt.Println(sliceValue1)
	fmt.Println(sliceValue2)
	fmt.Println(sliceValue3)
}

// 打印信息
[100 300]
[100 300]
&[100 300]