Java切片单偶数,go – 为什么具有奇数的切片容量与具有偶数的行为不同

简短的回答

它将切片容量四舍五入以填充分配的内存块.

答案很长

我们来看看Go1.5.1源代码:

s := l1

if n := len(l1) + len(l2) - cap(s); n > 0 {

s = growslice_n(s, n)

}

s = s[:len(l1)+len(l2)]

memmove(&s[len(l1)], &l2[0], len(l2)*sizeof(T))

更进一步,我们发现:

newcap := old.cap

if newcap+newcap < cap {

newcap = cap

} else {

for {

if old.len < 1024 {

newcap += newcap

} else {

newcap += newcap / 4

}

if newcap >= cap {

break

}

}

}

/* [...] */

capmem := roundupsize(uintptr(newcap) * uintptr(et.size))

newcap = int(capmem / uintptr(et.size))

// 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 <= 1024-8 {

return uintptr(class_to_size[size_to_class8[(size+7)>>3]])

} else {

return uintptr(class_to_size[size_to_class128[(size-1024+127)>>7]])

}

}

if size+_PageSize < size {

return size

}

return round(size, _PageSize)

}

When growing slice take into account size of the allocated memory block.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值