go1.17 slice扩容机制源码剖析详解

go1.17 slice扩容机制源码剖析详解

扩容问题

按照一般的说法,执行下面的代码,扩容状态是
在容量大于1024之后每次增加原来的四分之一,如下图

func Int64Grow() {
	intSlice := make([]int64,0)
	lastCap,nowCap := 0,0
	fmt.Printf("%10v %10v %10v \n","nowIdx","lastCap","nowCap")
	for i := 1 ;i < 3000 ; i++ {
		intSlice = append(intSlice,int64(i))
		nowCap = cap(intSlice)
		if lastCap != nowCap {
			fmt.Printf("%10d %10d %10d\n",i,len(intSlice),nowCap)
			lastCap = nowCap
		}
	}
}

在这里插入图片描述
但真实的执行效果,却是下面这样的

在这里插入图片描述
把切片的类型换成int32,又成了如下结果
在这里插入图片描述

上图中在切片容量的大小都是大于1024之后出现了问题,
网上也没有说明白,还是自己看一下源码

slice定义

type slice struct {
	array unsafe.Pointer
	len   int
	cap   int
}

make 一个 Slice

使用两层嵌套的if进行len和cap的范围检查
检查范围正常后申请一段内存并返回,否则panic

func makeslice(et *_type, len, cap int) unsafe.Pointer {
	mem, overflow := math.MulUintptr(et.size, uintptr(cap))
	if overflow || mem > maxAlloc || len < 0 || len > cap {
		// NOTE: Produce a 'len out of range' error instead of a
		// 'cap out of range' error when someone does make([]T, bignumber).
		// 'cap out of range' is true too, but since the cap is only being
		// supplied implicitly, saying len is clearer.
		// See golang.org/issue/4085.
		mem, overflow := math.MulUintptr(et.size, uintptr(len))
		if overflow || mem > maxAlloc || len < 0 {
			panicmakeslicelen()
		}
		panicmakeslicecap()
	}
	return mallocgc(mem, et, true)
}

func MulUintptr(a, b uintptr) (uintptr, bool)的主要作用就是防止溢出
uintptr 类型的返回值,返回ab的乘积
bool 类型的值表示a * b 是否溢出

// MulUintptr returns a * b and whether the multiplication overflowed.
// On supported platforms this is an intrinsic lowered by the compiler.
func MulUintptr(a, b uintptr) (uintptr, bool) {
	if a|b < 1<<(4*sys.PtrSize) || a == 0 {
		return a * b, false
	}
	overflow := b > MaxUintptr/a
	return a * b, overflow
}

扩容函数

内容都在注释中


// growslice handles slice growth during append.
// It is passed the slice element type, the old slice, and the desired new minimum capacity,
// and it returns a new slice with at least that capacity, with the old data
// copied into it.
// The new slice's length is set to the old slice's length,
// NOT to the new requested capacity.
// This is for codegen convenience. The old slice's length is used immediately
// to calculate where to write new values during an append.
// TODO: When the old backend is gone, reconsider this decision.
// The SSA backend might prefer the new length or to return only ptr/cap and save stack space.
func growslice(et *_type, old slice, cap int) slice {
	// 与切片容量没有绝对联系的代码暂时注释掉,不做讨论
	// if raceenabled {
	// 	callerpc := getcallerpc()
	// 	racereadrangepc(old.array, uintptr(old.len*int(et.size)), callerpc, funcPC(growslice))
	// }
	// if msanenabled {
	// 	msanread(old.array, uintptr(old.len*int(et.size)))
	// }

	if cap < old.cap {
		panic(errorString("growslice: cap out of range"))
	}

	// if et.size == 0 {
		// append should not create a slice with nil pointer but non-zero len.
		// We assume that append doesn't need to preserve old.array in this case.
	// 	return slice{unsafe.Pointer(&zerobase), old.len, cap}
	// }
	// 初始化新容量
	newcap := old.cap
    // 初始化原来的两倍容量
	doublecap := newcap + newcap
    if cap > doublecap {
        // 如果新容量大于 2 倍的旧容量,newcap就是新容量
		newcap = cap
	} else {
        // 如果原来的容量小于1024,则按照两倍进行扩容
		if old.cap < 1024 {
			newcap = doublecap
		} else {
            // newcap从旧容量开始循环增加原来的  1/4 , 直到newcap大于等于新申请的容量。
			// Check 0 < newcap to detect overflow
			// and prevent an infinite loop.
			for 0 < newcap && newcap < cap {
				newcap += newcap / 4
			}
            // 这种情况表明 newcap 溢出了,则newcap就是新申请容量。
			// Set newcap to the requested cap when
			// the newcap calculation overflowed.
			if newcap <= 0 {
				newcap = cap
			}
		}
	}
	// overflow,lenmem,newlenmem 与内存的申请有关,与切片容量没有绝对联系,下面都注释掉,不做讨论
	// var overflow bool
	var /*lenmem, newlenmem,*/ capmem uintptr
    // 
	// Specialize for common values of et.size.
	// For 1 we don't need any division/multiplication.
	// For sys.PtrSize, compiler will optimize division/multiplication into a shift by a constant.
	// For powers of 2, use a variable shift.
	switch {
        // 类型的大小是1个字节
	case et.size == 1:
        // lenmem = uintptr(old.len)
		// newlenmem = uintptr(cap)
        // 将新容量向上取整
		capmem = roundupsize(uintptr(newcap))
        // 如果 newcap 大于maxAlloc则表明溢出
		// overflow = uintptr(newcap) > maxAlloc
        // 获取计算后的新容量
		newcap = int(capmem)
        // 类型的大小是8个字节
	case et.size == sys.PtrSize:
        // 关于sys.PtrSize,粘贴一小段源码,以下三行来自:{GOROOT}\src\runtime\internal\sys\arch.go
        // // PtrSize is the size of a pointer in bytes - unsafe.Sizeof(uintptr(0)) but as an ideal constant.
		// // It is also the size of the machine's native word size (that is, 4 on 32-bit systems, 8 on 64-bit).
		// const PtrSize = 4 << (^uintptr(0) >> 63)
        // 综上所述,sys.PtrSize应该代表了指针类型,
        // 因为指针类型是8个字节,也是2的幂,所以要先判断是不是指针类型或是不是和指针类型的大小一样
		// lenmem = uintptr(old.len) * sys.PtrSize
		// newlenmem = uintptr(cap) * sys.PtrSize
        // 将新容量乘以指针的大小并向上取整
		capmem = roundupsize(uintptr(newcap) * sys.PtrSize)
        // 判断是否溢出,同上
		// overflow = uintptr(newcap) > maxAlloc/sys.PtrSize
		newcap = int(capmem / sys.PtrSize)
	case isPowerOfTwo(et.size):
        // 不是指针类型但类型大小还是2的倍数
		var shift uintptr
        // 如果指针的大小是8则表明是64位系统否则是32位
		if sys.PtrSize == 8 {
            // 计算这个表示类型的大小的数字的末尾有多少个0
            // 例如:现在类型是int32 ,4个字节,64位的系统,将会执行下面这个函数
            // 因为4->000000100,所以末尾有2个0,shift也就是2
			// Mask shift for better code generation.
			shift = uintptr(sys.Ctz64(uint64(et.size))) & 63
		} else {
			shift = uintptr(sys.Ctz32(uint32(et.size))) & 31
		}
		// lenmem = uintptr(old.len) << shift
		// newlenmem = uintptr(cap) << shift
		capmem = roundupsize(uintptr(newcap) << shift)
		// overflow = uintptr(newcap) > (maxAlloc >> shift)
		newcap = int(capmem >> shift) 
	default:
		// lenmem = uintptr(old.len) * et.size
		// newlenmem = uintptr(cap) * et.size
		capmem,_ /*overflow*/ = math.MulUintptr(et.size, uintptr(newcap))
		capmem = roundupsize(capmem)
		newcap = int(capmem / et.size)
	}
	
    // 下面这一段注释,主要是除了capmem > maxAlloc之外,还需要检查溢出 ,防止可能被用来触发段错误  
	// The check of overflow in addition to capmem > maxAlloc is needed
	// to prevent an overflow which can be used to trigger a segfault
	// on 32bit architectures with this example program:
	//
	// type T [1<<27 + 1]int64
	//
	// var d T
	// var s []T
	//
	// func main() {
	//   s = append(s, d, d, d, d)
	//   print(len(s), "\n")
	// }
	// if overflow || capmem > maxAlloc {
	// 		panic(errorString("growslice: cap out of range"))
	// }
    
    
	// 与编译器和GC有关、与申请内存时切片所使用的内存长度有关、与切片容量无关,暂不做讨论,自行翻译
	// var p unsafe.Pointer
	// if et.ptrdata == 0 {
	// 		p = mallocgc(capmem, nil, false)
	// 		// The append() that calls growslice is going to overwrite from old.len to cap (which will be the new length).
	// 		// Only clear the part that will not be overwritten.
	// 		memclrNoHeapPointers(add(p, newlenmem), capmem-newlenmem)
	// } else {
	// 		// Note: can't use rawmem (which avoids zeroing of memory), because then GC can scan uninitialized memory.
	// 		p = mallocgc(capmem, et, true)
	// 		if lenmem > 0 && writeBarrier.enabled {
	// 		// Only shade the pointers in old.array since we know the destination slice p
	// 		// only contains nil pointers because it has been cleared during alloc.
	// 		bulkBarrierPreWriteSrcOnly(uintptr(p), uintptr(old.array), lenmem-et.size+et.ptrdata)
	// 	}
	// }
	// memmove(p, old.array, lenmem)
	// 
	// return slice{p, old.len, newcap}
}
  • 内存对齐函数func roundupsize(size uintptr) uintptr
  • 把给定的大小扩大到更合适的大小且是8的倍数,下面就简称向上取整
  • 它的作用不只是内存对齐,
// Returns size of the memory block that mallocgc will allocate if you ask for the size.
func roundupsize(size uintptr) uintptr {
	if size < _MaxSmallSize {
		if size <= smallSizeMax-8 {
			return uintptr(class_to_size[size_to_class8[divRoundUp(size, smallSizeDiv)]])
		} else {
			return uintptr(class_to_size[size_to_class128[divRoundUp(size-smallSizeMax, largeSizeDiv)]])
		}
	}
	if size+_PageSize < size {
		return size
	}
	return alignUp(size, _PageSize)
}

使用到了两个数组 class_to_size·数组和size_to_class128所在的文件({GOROOT}\src\runtime\sizeclasses.go)下,是一个很长的数组

const (
	_MaxSmallSize   = 32768
	smallSizeDiv    = 8
	smallSizeMax    = 1024
	largeSizeDiv    = 128
	_NumSizeClasses = 68
	_PageShift      = 13
)

var class_to_size = [_NumSizeClasses]uint16{0, 8, 16, 24, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 256, 288, 320, 352, 384, 416, 448, 480, 512, 576, 640, 704, 768, 896, 1024, 1152, 1280, 1408, 1536, 1792, 2048, 2304, 2688, 3072, 3200, 3456, 4096, 4864, 5376, 6144, 6528, 6784, 6912, 8192, 9472, 9728, 10240, 10880, 12288, 13568, 14336, 16384, 18432, 19072, 20480, 21760, 24576, 27264, 28672, 32768}
var class_to_allocnpages = [_NumSizeClasses]uint8{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 3, 2, 3, 1, 3, 2, 3, 4, 5, 6, 1, 7, 6, 5, 4, 3, 5, 7, 2, 9, 7, 5, 8, 3, 10, 7, 4}
var class_to_divmagic = [_NumSizeClasses]uint32{0, ^uint32(0)/8 + 1, ^uint32(0)/16 + 1, ^uint32(0)/24 + 1, ^uint32(0)/32 + 1, ^uint32(0)/48 + 1, ^uint32(0)/64 + 1, ^uint32(0)/80 + 1, ^uint32(0)/96 + 1, ^uint32(0)/112 + 1, ^uint32(0)/128 + 1, ^uint32(0)/144 + 1, ^uint32(0)/160 + 1, ^uint32(0)/176 + 1, ^uint32(0)/192 + 1, ^uint32(0)/208 + 1, ^uint32(0)/224 + 1, ^uint32(0)/240 + 1, ^uint32(0)/256 + 1, ^uint32(0)/288 + 1, ^uint32(0)/320 + 1, ^uint32(0)/352 + 1, ^uint32(0)/384 + 1, ^uint32(0)/416 + 1, ^uint32(0)/448 + 1, ^uint32(0)/480 + 1, ^uint32(0)/512 + 1, ^uint32(0)/576 + 1, ^uint32(0)/640 + 1, ^uint32(0)/704 + 1, ^uint32(0)/768 + 1, ^uint32(0)/896 + 1, ^uint32(0)/1024 + 1, ^uint32(0)/1152 + 1, ^uint32(0)/1280 + 1, ^uint32(0)/1408 + 1, ^uint32(0)/1536 + 1, ^uint32(0)/1792 + 1, ^uint32(0)/2048 + 1, ^uint32(0)/2304 + 1, ^uint32(0)/2688 + 1, ^uint32(0)/3072 + 1, ^uint32(0)/3200 + 1, ^uint32(0)/3456 + 1, ^uint32(0)/4096 + 1, ^uint32(0)/4864 + 1, ^uint32(0)/5376 + 1, ^uint32(0)/6144 + 1, ^uint32(0)/6528 + 1, ^uint32(0)/6784 + 1, ^uint32(0)/6912 + 1, ^uint32(0)/8192 + 1, ^uint32(0)/9472 + 1, ^uint32(0)/9728 + 1, ^uint32(0)/10240 + 1, ^uint32(0)/10880 + 1, ^uint32(0)/12288 + 1, ^uint32(0)/13568 + 1, ^uint32(0)/14336 + 1, ^uint32(0)/16384 + 1, ^uint32(0)/18432 + 1, ^uint32(0)/19072 + 1, ^uint32(0)/20480 + 1, ^uint32(0)/21760 + 1, ^uint32(0)/24576 + 1, ^uint32(0)/27264 + 1, ^uint32(0)/28672 + 1, ^uint32(0)/32768 + 1}
var size_to_class8 = [smallSizeMax/smallSizeDiv + 1]uint8{0, 1, 2, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32}
var size_to_class128 = [(_MaxSmallSize-smallSizeMax)/largeSizeDiv + 1]uint8{32, 33, 34, 35, 36, 37, 37, 38, 38, 39, 39, 40, 40, 40, 41, 41, 41, 42, 43, 43, 44, 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 48, 48, 48, 49, 49, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 54, 54, 54, 54, 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58, 58, 58, 58, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67}

divRoundUp(n, a uintptr) uintptr函数在({GOROOT}\src\runtime\subs.go)

// divRoundUp returns ceil(n / a).
func divRoundUp(n, a uintptr) uintptr {
	// a is generally a power of two. This will get inlined and
	// the compiler will optimize the division.
	return (n + a - 1) / a
}

对扩容函数分析后的总结

以上代码总结一下:

在switch语句之前:

首先判断,如果newcap大于 2 倍的旧容量,接下来就使用newcap。

否则判断,如果旧切片的长度小于 1024,则newcap就是旧容量的两倍。

否则判断,如果旧切片长度大于等于 1024,则newcap从旧容量开始循环增加原来的 1/4 , 直到newcap大于等于新申请的容量。

如果newcap计算值溢出,接下来就使用newcap。

switch中:

  • 一个类型大小,如果是1,

    • 那么它最终的容量是经过func roundupsize(size uintptr) uintptr函数向上取整
  • 如果一个类型大小是8:

    • 它的最终容量就是在switch之前的计算所得到的容量大小乘以8,得到所需内存长度,
    • 再将内存长度roundupsize(size uintptr)向上取整之后的值除以8(相当于将容量向上取整之后再还原)
  • 一个非零字节大小类型、它的字节长度既不是1、又不是8(机器的指针类型),而且是二的倍数:

    • 计算该类型所占字节大小的二进制尾部0的个数(记作shift)
    • 再将switch之前的已经计算好的新容量,向左位移shift位,并向上对8取整,(以获得新容量所需要内存的字节长度)
    • 最终的切片容量大小是:得新容量所需要内存的字节长度 右移 shift位的值
  • 如果以上都不符合:

    • 它的最终容量就是在switch之前的计算所得到的容量大小乘以它的类型大小,得到所需内存长度,并其大小判断是否溢出
    • 在向上取整后除以它的类型大小

猜测:switch语句块的作用可能是根据不同的类型大小计算合适的内存大小,再转换成实际的容量

为什么要这样做,这样会不会造成内存浪费?

我们可以想一想,go的开发者们肯定也会想到这些,所以,我们还是去源码中找找答案
func roundupsize(size uintptr) uintptr函数中,使用到了两个数组 class_to_size·数组和size_to_class128
我们跳转到其所在的文件,所在的文件({GOROOT}\src\runtime\sizeclasses.go)下,

有这两个数组以及其他别的地方用到的数组的声明信息,还有go官方
文件头部的注释有一个各种类型大小与内存的关系的表,这个表很长,如下图(只截取一部分)
在这里插入图片描述

可以初步得到结论,现在这种情况是go开发人员经过分析后得出的。
但是文件的第一行有这样一行注释:

// Code generated by mksizeclasses.go; DO NOT EDIT.

这说明了我们需要找到mksizeclasses.go中去看看

mksizeclasses.go中映入眼帘的注释给了我们答案

在这里插入图片描述

有道翻译
为小的malloc大小的类生成表。
看到malloc。 概述。
选择size类是为了舍入分配
请求到下一个大小的类最多浪费12.5% (1.125x)。
每个size类都有自己分配的页数
当需要size类的新对象时,将其切碎。
这个页数是被选择的,这样就可以分割
进入给定大小的对象的页面最多浪费12.5% (1.125x)
的内存。 这里的边界没有必要是
同上。
这两种浪费源成倍增加,这是最坏的情况
对于上述的限制将是一些拨款
大小可能有26.6% (1.266x)的开销。
在实践中,只有一种浪费对一个
给定大小(大小< 512主要是在汇总中浪费,
大小> 512浪费主要在页面切割)。
对于非常小的尺寸,对齐约束强制
开销更高。

  • ok,问题解决
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值