string類型和[]byte類型是咱們編程時最常使用到的數據結構。本文將探討二者之間的轉換方式,經過分析它們之間的內在聯繫來撥開迷霧。編程
go中string與[]byte的互換,相信每一位gopher都能馬上想到如下的轉換方式,咱們將之稱爲標準轉換。數組
// string to []byte s1 := "hello" b := []byte(s1) // []byte to string s2 := string(b)
經過unsafe和reflect包,能夠實現另一種轉換方式,咱們將之稱爲強轉換(也經常被人稱做黑魔法)。安全
func String2Bytes(s string) []byte { sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) bh := reflect.SliceHeader{ Data: sh.Data, Len: sh.Len, Cap: sh.Len, } return *(*[]byte)(unsafe.Pointer(&bh)) } func Bytes2String(b []byte) string { return *(*string)(unsafe.Pointer(&b)) }
既然有兩種轉換方式,那麼咱們有必要對它們作性能對比。數據結構
// 測試強轉換功能 func TestBytes2String(t *testing.T) { x := []byte("Hello Gopher!") y := Bytes2String(x) z := string(x) if y != z { t.Fail() } } // 測試強轉換功能 func TestString2Bytes(t *testing.T) { x := "Hello Gopher!" y := String2Bytes(x) z := []byte(x) if !bytes.Equal(y, z) { t.Fail() } } // 測試標準轉換string()性能 func Benchmark_NormalBytes2String(b *testing.B) { x := []byte("Hello Gopher! Hello Gopher! Hello Gopher!") for i := 0; i < b.N; i++ { _ = string(x) } } // 測試強轉換[]byte到string性能 func Benchmark_Byte2String(b *testing.B) { x := []byte("Hello Gopher! Hello Gopher! Hello Gopher!") for i := 0; i < b.N; i++ { _ = Bytes2String(x) } } // 測試標準轉換[]byte性能 func Benchmark_NormalString2Bytes(b *testing.B) { x := "Hello Gopher! Hello Gopher! Hello Gopher!" for i := 0; i < b.N; i++ { _ = []byte(x) } } // 測試強轉換string到[]byte性能 func Benchmark_String2Bytes(b *testing.B) { x := "Hello Gopher! Hello Gopher! Hello Gopher!" for i := 0; i < b.N; i++ { _ = String2Bytes(x) } }
測試結果以下併發
$ go test -bench="." -benchmem goos: darwin goarch: amd64 pkg: workspace/example/stringBytes Benchmark_NormalBytes2String-8 38363413 27.9 ns/op 48 B/op 1 allocs/op Benchmark_Byte2String-8 1000000000 0.265 ns/op 0 B/op 0 allocs/op Benchmark_NormalString2Bytes-8 32577080 34.8 ns/op 48 B/op 1 allocs/op Benchmark_String2Bytes-8 1000000000 0.532 ns/op 0 B/op 0 allocs/op PASS ok workspace/example/stringBytes 3.170s
注意,-benchmem
能夠提供每次操做分配內存的次數,以及每次操做分配的字節數。ide
當x的數據均爲"Hello Gopher!"時,測試結果以下函數
$ go test -bench="." -benchmem goos: darwin goarch: amd64 pkg: workspace/example/stringBytes Benchmark_NormalBytes2String-8 245907674 4.86 ns/op 0 B/op 0 allocs/op Benchmark_Byte2String-8 1000000000 0.266 ns/op 0 B/op 0 allocs/op Benchmark_NormalString2Bytes-8 202329386 5.92 ns/op 0 B/op 0 allocs/op Benchmark_String2Bytes-8 1000000000 0.532 ns/op 0 B/op 0 allocs/op PASS ok workspace/example/stringBytes 4.383s
強轉換方式的性能會明顯優於標準轉換。佈局
讀者能夠思考如下問題性能
1.爲啥強轉換性能會比標準轉換好?測試
2.爲啥在上述測試中,當x的數據較大時,標準轉換方式會有一次分配內存的操做,從而致使其性能更差,而強轉換方式卻不受影響?
3.既然強轉換方式性能這麼好,爲啥go語言提供給咱們使用的是標準轉換方式?
要回答以上三個問題,首先要明白是string和[]byte在go中究竟是什麼。
在go中,byte是uint8的別名,在go標準庫builtin中有以下說明:
// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is // used, by convention, to distinguish byte values from 8-bit unsigned // integer values. type byte = uint8
在go的源碼中src/runtime/slice.go
,slice的定義以下:
type slice struct { array unsafe.Pointer len int cap int }
array是底層數組的指針,len表示長度,cap表示容量。對於[]byte來講,array指向的就是byte數組。
關於string類型,在go標準庫builtin中有以下說明:
// string is the set of all strings of 8-bit bytes, conventionally but not // necessarily representing UTF-8-encoded text. A string may be empty, but // not nil. Values of string type are immutable. type string string
翻譯過來就是:string是8位字節的集合,一般但不必定表明UTF-8編碼的文本。string能夠爲空,可是不能爲nil。string的值是不能改變的。
在go的源碼中src/runtime/string.go
,string的定義以下:
type stringStruct struct { str unsafe.Pointer len int }
stringStruct表明的就是一個string對象,str指針指向的是某個數組的首地址,len表明的數組長度。那麼這個數組是什麼呢?咱們能夠在實例化stringStruct對象時找到答案。
//go:nosplit func gostringnocopy(str *byte) string { ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)} s := *(*string)(unsafe.Pointer(&ss)) return s }
能夠看到,入參str指針就是指向byte的指針,那麼咱們能夠肯定string的底層數據結構就是byte數組。
綜上,string與[]byte在底層結構上是很是的相近(後者的底層表達僅多了一個cap屬性,所以它們在內存佈局上是可對齊的),這也就是爲什麼builtin中內置函數copy會有一種特殊狀況copy(dst []byte, src string) int
的緣由了。
// The copy built-in function copies elements from a source slice into a // destination slice. (As a special case, it also will copy bytes from a // string to a slice of bytes.) The source and destination may overlap. Copy // returns the number of elements copied, which will be the minimum of // len(src) and len(dst). func copy(dst, src []Type) int
對於[]byte與string而言,二者之間最大的區別就是string的值不能改變。這該如何理解呢?下面經過兩個例子來講明。
對於[]byte來講,如下操做是可行的:
b := []byte("Hello Gopher!") b [1] = 'T'
string,修改操做是被禁止的:
s := "Hello Gopher!" s[1] = 'T'
而string能支持這樣的操做:
s := "Hello Gopher!" s = "Tello Gopher!"
字符串的值不能被更改,但能夠被替換。 string在底層都是結構體stringStruct{str: str_point, len: str_len}
,string結構體的str指針指向的是一個字符常量的地址, 這個地址裏面的內容是不能夠被改變的,由於它是隻讀的,可是這個指針能夠指向不一樣的地址。
那麼,如下操做的含義是不一樣的:
s := "S1" // 分配存儲"S1"的內存空間,s結構體裏的str指針指向這塊內存 s = "S2" // 分配存儲"S2"的內存空間,s結構體裏的str指針轉爲指向這塊內存 b := []byte{1} // 分配存儲'1'數組的內存空間,b結構體的array指針指向這個數組。 b = []byte{2} // 將array的內容改成'2'
圖解以下
由於string的指針指向的內容是不能夠更改的,因此每更改一次字符串,就得從新分配一次內存,以前分配的空間還須要gc回收,這是致使string相較於[]byte操做低效的根本緣由。
[]byte(string)的實現(源碼在src/runtime/string.go
中)
// The constant is known to the compiler. // There is no fundamental theory behind this number. const tmpStringBufSize = 32 type tmpBuf [tmpStringBufSize]byte func stringtoslicebyte(buf *tmpBuf, s string) []byte { var b []byte if buf != nil && len(s) <= len(buf) { *buf = tmpBuf{} b = buf[:len(s)] } else { b = rawbyteslice(len(s)) } copy(b, s) return b } // rawbyteslice allocates a new byte slice. The byte slice is not zeroed. func rawbyteslice(size int) (b []byte) { cap := roundupsize(uintptr(size)) p := mallocgc(cap, nil, false) if cap != uintptr(size) { memclrNoHeapPointers(add(p, uintptr(size)), cap-uintptr(size)) } *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)} return }
這裏有兩種狀況:s的長度是否大於32。當大於32時,go須要調用mallocgc分配一塊新的內存(大小由s決定),這也就回答了上文中的問題2:當x的數據較大時,標準轉換方式會有一次分配內存的操做。
最後經過copy函數實現string到[]byte的拷貝,具體實如今src/runtime/slice.go
中的slicestringcopy
方法。
func slicestringcopy(to []byte, fm string) int { if len(fm) == 0 || len(to) == 0 { return 0 } // copy的長度取決與string和[]byte的長度最小值 n := len(fm) if len(to) < n { n = len(to) } // 若是開啓了競態檢測 -race if raceenabled { callerpc := getcallerpc() pc := funcPC(slicestringcopy) racewriterangepc(unsafe.Pointer(&to[0]), uintptr(n), callerpc, pc) } // 若是開啓了memory sanitizer -msan if msanenabled { msanwrite(unsafe.Pointer(&to[0]), uintptr(n)) } // 該方法將string的底層數組從頭部複製n個到[]byte對應的底層數組中去(這裏就是copy實現的核心方法,在彙編層面實現 源文件爲memmove_*.s) memmove(unsafe.Pointer(&to[0]), stringStructOf(&fm).str, uintptr(n)) return n }
copy實現過程圖解以下
string([]byte)的實現(源碼也在src/runtime/string.go
中)
// Buf is a fixed-size buffer for the result, // it is not nil if the result does not escape. func slicebytetostring(buf *tmpBuf, b []byte) (str string) { l := len(b) if l == 0 { // Turns out to be a relatively common case. // Consider that you want to parse out data between parens in "foo()bar", // you find the indices and convert the subslice to string. return "" } // 若是開啓了競態檢測 -race if raceenabled { racereadrangepc(unsafe.Pointer(&b[0]), uintptr(l), getcallerpc(), funcPC(slicebytetostring)) } // 若是開啓了memory sanitizer -msan if msanenabled { msanread(unsafe.Pointer(&b[0]), uintptr(l)) } if l == 1 { stringStructOf(&str).str = unsafe.Pointer(&staticbytes[b[0]]) stringStructOf(&str).len = 1 return } var p unsafe.Pointer if buf != nil && len(b) <= len(buf) { p = unsafe.Pointer(buf) } else { p = mallocgc(uintptr(len(b)), nil, false) } stringStructOf(&str).str = p stringStructOf(&str).len = len(b) // 拷貝字節數組至字符串 memmove(p, (*(*slice)(unsafe.Pointer(&b))).array, uintptr(len(b))) return } // 實例stringStruct對象 func stringStructOf(sp *string) *stringStruct { return (*stringStruct)(unsafe.Pointer(sp)) }
可見,當數組長度超過32時,一樣須要調用mallocgc分配一塊新內存。最後經過memmove完成拷貝。
在go中,任何類型的指針\T均可以轉換爲unsafe.Pointer類型的指針,它能夠存儲任何變量的地址。同時,unsafe.Pointer類型的指針也能夠轉換回普通指針,並且能夠沒必要和以前的類型\T相同。另外,unsafe.Pointer類型還能夠轉換爲uintptr類型,該類型保存了指針所指向地址的數值,從而可使咱們對地址進行數值計算。以上就是強轉換方式的實現依據。
而string和slice在reflect包中,對應的結構體是reflect.StringHeader和reflect.SliceHeader,它們是string和slice的運行時表達。
type StringHeader struct { Data uintptr Len int } type SliceHeader struct { Data uintptr Len int Cap int }
從string和slice的運行時表達能夠看出,除了SilceHeader多了一個int類型的Cap字段,Date和Len字段是一致的。因此,它們的內存佈局是可對齊的,這說明咱們就能夠直接經過unsafe.Pointer進行轉換。
[]byte轉string圖解
string轉[]byte圖解
<u>Q1. 爲啥強轉換性能會比標準轉換好?</u>
對於標準轉換,不管是從[]byte轉string仍是string轉[]byte都會涉及底層數組的拷貝。而強轉換是直接替換指針的指向,從而使得string和[]byte指向同一個底層數組。這樣,固然後者的性能會更好。
<u>Q2. 爲啥在上述測試中,當x的數據較大時,標準轉換方式會有一次分配內存的操做,從而致使其性能更差,而強轉換方式卻不受影響?</u>
標準轉換時,當數據長度大於32個字節時,須要經過mallocgc申請新的內存,以後再進行數據拷貝工做。而強轉換隻是更改指針指向。因此,當轉換數據較大時,二者性能差距會越發明顯。
<u>Q3. 既然強轉換方式性能這麼好,爲啥go語言提供給咱們使用的是標準轉換方式?</u>
首先,咱們須要知道Go是一門類型安全的語言,而安全的代價就是性能的妥協。可是,性能的對比是相對的,這點性能的妥協對於如今的機器而言微乎其微。另外強轉換的方式,會給咱們的程序帶來極大的安全隱患。
以下示例
a := "hello" b := String2Bytes(a) b[0] = 'H'
a是string類型,前面咱們講到它的值是不可修改的。經過強轉換將a的底層數組賦給b,而b是一個[]byte類型,它的值是能夠修改的,因此這時對底層數組的值進行修改,將會形成嚴重的錯誤(經過defer+recover也不能捕獲)。
unexpected fault address 0x10b6139 fatal error: fault [signal SIGBUS: bus error code=0x2 addr=0x10b6139 pc=0x1088f2c]
<u>Q4. 爲啥string要設計爲不可修改的?</u>
我認爲有必要思考一下該問題。string不可修改,意味它是隻讀屬性,這樣的好處就是:在併發場景下,咱們能夠在不加鎖的控制下,屢次使用同一字符串,在保證高效共享的狀況下而不用擔憂安全問題。