在go中string是不可变的,这意味着对string发生改变的操作实际上都是通过分配新的string去实现的
在string内存分配上,对于小对象分配到栈,大对象分配到堆中
string在go中的结构其实很简单,就是一个指向实际数据的指针以及字符串的长度。
type stringStruct struct {str unsafe.Pointerlen 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,则返回0if 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 byteif GOOS == "plan9" {p := (*[maxAlloc/2 - 1]byte)(unsafe.Pointer(s))l := 0for p[l] != 0 {l++}return l}// 最小页大小const pageSize = 4096offset := 0ptr := 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数量为长度,指针为字符数组转换为stringt := *(*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 += safeLensafeLen = 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 ""}// 分配对应长度的strings, b := rawstring(l)// 复制字符指针的内容到新分配的stringmemmove(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 := 0l := 0count := 0for 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().stackreturn 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
- https://www.cnblogs.com/promise6522/archive/2012/03/22/2412686.html
- https://www.zhihu.com/question/54664311/answer/1978680475