在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