Golang黑科技之——string與[]byte轉換

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

我們知道,相對於C語言,golang是型別安全的語言。但是安全的代價就是效能的妥協。
下面我們通過Golang中的“黑科技”來一窺Golang不想讓我們看到的“秘密”——string的底層資料。
通過reflect包,我們可以知道,在Golang底層,string和slice其實都是struct:

type SliceHeader struct {    Data uintptr    Len  int    Cap  int}type StringHeader struct {    Data uintptr    Len  int}

其中Data是一個指標,指向實際的資料地址,Len表示資料長度。
但是,在string和[]byte轉換過程中,Golang究竟悄悄幫我們做了什麼,來達到安全的目的?
在Golang語言規範裡面,string資料是禁止修改的,試圖通過&s[0], &b[0]取得string和slice資料指標地址也是不能通過編譯的。
下面,我們就通過Golang的“黑科技”來一窺Golang背後的“秘密”。

//return GoString's buffer slice(enable modify string)func StringBytes(s string) Bytes {    return *(*Bytes)(unsafe.Pointer(&s))}// convert b to string without copyfunc BytesString(b []byte) String {    return *(*String)(unsafe.Pointer(&b))}// returns &s[0], which is not allowed in gofunc StringPointer(s string) unsafe.Pointer {    p := (*reflect.StringHeader)(unsafe.Pointer(&s))    return unsafe.Pointer(p.Data)}// returns &b[0], which is not allowed in gofunc BytesPointer(b []byte) unsafe.Pointer {    p := (*reflect.SliceHeader)(unsafe.Pointer(&b))    return unsafe.Pointer(p.Data)}

以上4個函數的神奇之處在於,通過unsafe.Pointer和reflect.XXXHeader取到了資料首地址,並實現了string和[]byte的直接轉換(這些操作在語言層面是禁止的)。
下面我們就通過這幾個“黑科技”來測試一下語言底層的秘密:

func TestPointer(t *testing.T) {    s := []string{        "",        "",        "hello",        "hello",        fmt.Sprintf(""),        fmt.Sprintf(""),        fmt.Sprintf("hello"),        fmt.Sprintf("hello"),    }    fmt.Println("String to bytes:")    for i, v := range s {        b := unsafe.StringBytes(v)        b2 := []byte(v)        if b.Writeable() {            b[0] = 'x'        }        fmt.Printf("%d\ts=%5s\tptr(v)=%-12v\tptr(StringBytes(v)=%-12v\tptr([]byte(v)=%-12v\n",            i, v, unsafe.StringPointer(v), b.Pointer(), unsafe.BytesPointer(b2))    }    b := [][]byte{        []byte{},        []byte{'h', 'e', 'l', 'l', 'o'},    }    fmt.Println("Bytes to string:")    for i, v := range b {        s1 := unsafe.BytesString(v)        s2 := string(v)        fmt.Printf("%d\ts=%5s\tptr(v)=%-12v\tptr(StringBytes(v)=%-12v\tptr(string(v)=%-12v\n",            i, s1, unsafe.BytesPointer(v), s1.Pointer(), unsafe.StringPointer(s2))    }}const N = 3000000func Benchmark_Normal(b *testing.B) {    for i := 1; i < N; i++ {        s := fmt.Sprintf("12345678901234567890123456789012345678901234567890")        bb := []byte(s)        bb[0] = 'x'        s = string(bb)        s = s    }}func Benchmark_Direct(b *testing.B) {    for i := 1; i < N; i++ {        s := fmt.Sprintf("12345678901234567890123456789012345678901234567890")        bb := unsafe.StringBytes(s)        bb[0] = 'x'        s = s    }}//test result//String to bytes://0 s=      ptr(v)=0x51bd70     ptr(StringBytes(v)=0x51bd70     ptr([]byte(v)=0xc042021c58//1 s=      ptr(v)=0x51bd70     ptr(StringBytes(v)=0x51bd70     ptr([]byte(v)=0xc042021c58//2 s=hello ptr(v)=0x51c2fa     ptr(StringBytes(v)=0x51c2fa     ptr([]byte(v)=0xc042021c58//3 s=hello ptr(v)=0x51c2fa     ptr(StringBytes(v)=0x51c2fa     ptr([]byte(v)=0xc042021c58//4 s=      ptr(v)=<nil>        ptr(StringBytes(v)=<nil>        ptr([]byte(v)=0xc042021c58//5 s=      ptr(v)=<nil>        ptr(StringBytes(v)=<nil>        ptr([]byte(v)=0xc042021c58//6 s=xello ptr(v)=0xc0420444b5 ptr(StringBytes(v)=0xc0420444b5 ptr([]byte(v)=0xc042021c58//7 s=xello ptr(v)=0xc0420444ba ptr(StringBytes(v)=0xc0420444ba ptr([]byte(v)=0xc042021c58//Bytes to string://0 s=      ptr(v)=0x5c38b8     ptr(StringBytes(v)=0x5c38b8     ptr(string(v)=<nil>//1 s=hello ptr(v)=0xc0420445e0 ptr(StringBytes(v)=0xc0420445e0 ptr(string(v)=0xc042021c38//Benchmark_Normal-4    1000000000           0.87 ns/op//Benchmark_Direct-4    2000000000           0.24 ns/op

結論如下:
1.string常量會在編譯期分配到唯讀段,對應資料地址不可寫入,並且相同的string常量不會重複儲存。
2.fmt.Sprintf產生的字串分配在堆上,對應資料地址可修改。
3.常量Null 字元串有資料地址,動態產生的字串沒有設定資料地址
4.Golang string和[]byte轉換,會將資料複製到堆上,返回資料指向複製的資料
5.動態產生的字串,即使內容一樣,資料也是在不同的空間
6.只有動態產生的string,資料可以被黑科技修改
8.string和[]byte通過複製轉換,效能損失接近4倍

我將測試代碼放在這裡,歡迎參考:
https://github.com/vipally/gx/blob/master/unsafe/string_test.go

參考資料:
[1] Go語言黑魔法 http://studygolang.com/articles/2909

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.