go string 实现

在go中string是不可变的,这意味着对string发生改变的操作实际上都是通过分配新的string去实现的

在string内存分配上,对于小对象分配到栈,大对象分配到堆中

string在go中的结构其实很简单,就是一个指向实际数据的指针以及字符串的长度。

type stringStruct struct {
	str unsafe.Pointer
	len int
}

创建

先创建string Struct,然后转换为string

以字符指针为字符串指针,到第一个null byte偏移量为长度

func gostringnocopy(str *byte) string {
	ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
	s := *(*string)(unsafe.Pointer(&ss))
	return s
}

找到第一个非null byte的位置

func findnull(s *byte) int {
  // 若指针为nil,则返回0
	if s == nil {
		return 0
	}

	// Avoid IndexByteString on Plan 9 because it uses SSE instructions
	// on x86 machines, and those are classified as floating point instructions,
	// which are illegal in a note handler.
  // 对于plan9系统,IndexByteString是非法的
  // 因此需要转换为字符数组,遍历直到发现null byte
	if GOOS == "plan9" {
		p := (*[maxAlloc/2 - 1]byte)(unsafe.Pointer(s))
		l := 0
		for p[l] != 0 {
			l++
		}
		return l
	}

  // 最小页大小
	const pageSize = 4096

	offset := 0
	ptr := unsafe.Pointer(s)
	// IndexByteString uses wide reads, so we need to be careful
	// with page boundaries. Call IndexByteString on
	// [ptr, endOfPage) interval.
  // 计算到达下页剩余的byte数量
	safeLen := int(pageSize - uintptr(ptr)%pageSize)

	for {
    // 以本页剩余byte数量为长度,指针为字符数组转换为string
		t := *(*string)(unsafe.Pointer(&stringStruct{ptr, safeLen}))
		// 尝试找到本页字符串中的null byte位置,如果找到,返回之前遍历过的偏移量加找到的位置
		if i := bytealg.IndexByteString(t, 0); i != -1 {
			return offset + i
		}
		// 移动指针到下页
		ptr = unsafe.Pointer(uintptr(ptr) + uintptr(safeLen))
    // 更新偏移量和剩余byte数量为页大小
		offset += safeLen
		safeLen = pageSize
	}
}

指定大小进行创建string

func rawstring(size int) (s string, b []byte) {
  // 分配指定大小的字符数组。
  // 小对象分配到每个p cache的空闲list,大对象(>32kB)分配到堆中
	p := mallocgc(uintptr(size), nil, false)
  // 转换为指定大小string和字符数组
	return unsafe.String((*byte)(p), size), unsafe.Slice((*byte)(p), size)
}

C string转换为Go string

func gostring(p *byte) string {
  // 找到字符串长度
	l := findnull(p)
	if l == 0 {
		return ""
	}
  
  // 分配对应长度的string
	s, b := rawstring(l)
  
  // 复制字符指针的内容到新分配的string
	memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
	return s
}

拼接

在缓存能承载拼接字符串时,直接用缓存去储存拼接字符串。这能防止频繁的堆分配,并减少额外的gc开销

缓存不行才会重新分配内存

// concatstrings implements a Go string concatenation x+y+z+...
// The operands are passed in the slice a.
// If buf != nil, the compiler has determined that the result does not
// escape the calling function, so the string data can be stored in buf
// if small enough.
func concatstrings(buf *tmpBuf, a []string) string {
	idx := 0
	l := 0
	count := 0
  
	for i, x := range a {
    // 判断拼接字符串长度是否合法
		n := len(x)
		if n == 0 {
			continue
		}
		if l+n < l {
			throw("string concatenation too long")
		}
    
    // 递增总字符串长度
		l += n
    // 递增非空字符串数量
		count++
    // 记录最后非空字符串索引
		idx = i
	}
  // 如果非空字符串数量为0,则返回空
	if count == 0 {
		return ""
	}

	// If there is just one string and either it is not on the stack
	// or our result does not escape the calling frame (buf != nil),
	// then we can return that string directly.
  // 如果仅有一个非空字符串,并且它不需要转义当前帧(buf != nil)或者它不在栈上(!stringDataOnStack(a[idx])),则直接返回该字符串
	if count == 1 && (buf != nil || !stringDataOnStack(a[idx])) {
		return a[idx]
	}
  
  // 分配总字符串长度的string,并将拼接字符串复制到新string的字符数组中
	s, b := rawstringtmp(buf, l)
	for _, x := range a {
		copy(b, x)
		b = b[len(x):]
	}
	return s
}

func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
	if buf != nil && l <= len(buf) {
		b = buf[:l]
		s = slicebytetostringtmp(&b[0], len(b))
	} else {
		s, b = rawstring(l)
	}
	return
}

// stringDataOnStack reports whether the string's data is
// stored on the current goroutine's stack.
func stringDataOnStack(s string) bool {
	ptr := uintptr(unsafe.Pointer(unsafe.StringData(s)))
	stk := getg().stack
	return stk.lo <= ptr && ptr < stk.hi
}

string常见实现方式对比

eager copy

在每次拷贝时将原string对应内容以及所持有的动态资源完整复制

优点

  • 实现简单
  • string互相独立,不会相互影响

缺点

  • 字符串较大时,比较浪费空间
copy on write

写时复制只有在string需要对对象进行修改时才会执行复制

在实现中,需要记录string引用的数量refCount,每当string被引用一次,refCount++。而当需要对string做修改时,则重新申请空间并复制原字符串,refCount–。最终当refCount为0时回收内存

优点

  • 字符串空间较大时,减少了分配、复制字符串时间和空间

缺点

  • 记录string引用的数量需要原子操作,带来性能损耗
  • 在某些情况下反而会带来额外开销。比如线程1访问字符串A,线程2访问字符串B,字符串A、B共享同一片内容,当线程1、2都修改同一片字符串,就会都进行两次复制,外加最开始的分配和最后的内存释放,这比eager copy的两次内存分配的代价更高
Small String Optimization

基于字符串大多数较短的特性,利用string本身的栈空间来储存短字符串;当字符串长度大于临界点时,则使用eager copy

优点

  • 短字符串时,无动态内存分配

缺点

  • string对象占用空间更大

Ref

  1. https://www.cnblogs.com/promise6522/archive/2012/03/22/2412686.html
  2. https://www.zhihu.com/question/54664311/answer/1978680475
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值