欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

go中實(shí)現(xiàn)字符切片和字符串互轉(zhuǎn)

 更新時(shí)間:2023年11月20日 09:47:50   作者:~kiss~  
這篇文章主要為大家詳細(xì)介紹了go語言中如何實(shí)現(xiàn)字符切片和字符串互轉(zhuǎn),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下

Go 1.21

// 返回一個(gè)Slice,它的底層數(shù)組自ptr開始,長度和容量都是len
func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
// 返回一個(gè)指針,指向底層的數(shù)組
func SliceData(slice []ArbitraryType) *ArbitraryType
// 生成一個(gè)字符串,底層的數(shù)組開始自ptr,長度是len
// returns a string value whose underlying bytes start at ptr and whose length is len
// The len argument must be of integer type or an untyped constant
// A constant len argument must be non-negative and representable by a value of type int
// if it is an untyped constant it is given type int
// At run time, if len is negative, or if ptr is nil and len is not zero, a run-time panic occurs
// Since Go strings are immutable, the bytes passed to String must not be modified afterwards
func String(ptr *byte, len IntegerType) string
// 返回字符串底層的數(shù)組
// returns a pointer to the underlying bytes of str
// For an empty string the return value is unspecified, and may be nil.
// Since Go strings are immutable, the bytes returned by StringData must not be modified.
func StringData(str string) *byte

Go 1.20

廢棄兩個(gè)類型SliceHeader和StringHeader

Go 1.19

string.SliceHeader和string.StringHeader經(jīng)常用在 slice of byte 和 string 高效互轉(zhuǎn)場(chǎng)景

// go1.18.3/src/reflect/value.go
// SliceHeader is the runtime representation of a slice.
// It cannot be used safely or portably and its representation may
// change in a later release.
// Moreover, the Data field is not sufficient to guarantee the data
// it references will not be garbage collected, so programs must keep
// a separate, correctly typed pointer to the underlying data.
type SliceHeader struct {                                                                                      
    Data uintptr
    Len  int
    Cap  int
}

// StringHeader is the runtime representation of a string.
// It cannot be used safely or portably and its representation may
// change in a later release.
// Moreover, the Data field is not sufficient to guarantee the data
// it references will not be garbage collected, so programs must keep
// a separate, correctly typed pointer to the underlying data.
type StringHeader struct {                                                                                     
    Data uintptr
    Len  int
}

Slice比String多一個(gè)Cap字段

兩個(gè)的數(shù)據(jù)都存儲(chǔ)在Data數(shù)組中

實(shí)現(xiàn)方式

方式1

string(bytes)或[]byte(str)

性能不佳

方式2

// toBytes performs unholy acts to avoid allocations
func toBytes(s string) []byte {
    return *(*[]byte)(unsafe.Pointer(&s))
}
// toString performs unholy acts to avoid allocations
func toString(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

方式3

func SliceByteToString(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}
func StringToSliceByte(s string) []byte {
    x := (*[2]uintptr)(unsafe.Pointer(&s))
    h := [3]uintptr{x[0], x[1], x[1]}
    return *(*[]byte)(unsafe.Pointer(&h))
}

方式4

func Clone(s string) string {
    if len(s) == 0 {
        return ""
    }
    b := make([]byte, len(s))
    copy(b, s)
    return *(*string)(unsafe.Pointer(&b))
}

性能測(cè)試

var L = 1024 * 1024
var str = strings.Repeat("a", L)
var s = bytes.Repeat([]byte{'a'}, L)
var str2 string
var s2 []byte
func BenchmarkString2Slice(b *testing.B) {
    for i := 0; i < b.N; i++ {
        bt := []byte(str)
        if len(bt) != L {
            b.Fatal()
        }
    }
}
func BenchmarkString2SliceReflect(b *testing.B) {
    for i := 0; i < b.N; i++ {
        bt := *(*[]byte)(unsafe.Pointer(&str))
        if len(bt) != L {
            b.Fatal()
        }
    }
}
func BenchmarkString2SliceUnsafe(b *testing.B) {
    for i := 0; i < b.N; i++ {
        bt := unsafe.Slice(unsafe.StringData(str), len(str))
        if len(bt) != L {
            b.Fatal()
        }
    }
}
func BenchmarkSlice2String(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ss := string(s)
        if len(ss) != L {
            b.Fatal()
        }
    }
}
func BenchmarkSlice2StringReflect(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ss := *(*string)(unsafe.Pointer(&s))
        if len(ss) != L {
            b.Fatal()
        }
    }
}
func BenchmarkSlice2StringUnsafe(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ss := unsafe.String(unsafe.SliceData(s), len(str))
        if len(ss) != L {
            b.Fatal()
        }
    }
}

官方出品必然是好東西,所以相信GO1.21即可

到此這篇關(guān)于go中實(shí)現(xiàn)字符切片和字符串互轉(zhuǎn)的文章就介紹到這了,更多相關(guān)go字符切片和字符串互轉(zhuǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Golang中基于HTTP協(xié)議的網(wǎng)絡(luò)服務(wù)

    Golang中基于HTTP協(xié)議的網(wǎng)絡(luò)服務(wù)

    HTTP協(xié)議是基于TCP/IP協(xié)議棧的,并且它也是一個(gè)面向普通文本的協(xié)議。這篇文章主要詳細(xì)介紹了Golang中基于HTTP協(xié)議的網(wǎng)絡(luò)服務(wù),感興趣的小伙伴可以借鑒一下
    2023-04-04
  • 淺談beego默認(rèn)處理靜態(tài)文件性能低下的問題

    淺談beego默認(rèn)處理靜態(tài)文件性能低下的問題

    下面小編就為大家?guī)硪黄獪\談beego默認(rèn)處理靜態(tài)文件性能低下的問題。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-06-06
  • golang反向代理設(shè)置host不生效的問題解決

    golang反向代理設(shè)置host不生效的問題解決

    在使用golang的httputil做反向代理的時(shí)候,發(fā)現(xiàn)一個(gè)奇怪的現(xiàn)象,上游網(wǎng)關(guān)必須要設(shè)置host才行,不設(shè)置host的話,golang服務(wù)反向代理請(qǐng)求下游會(huì)出現(xiàn)http 503錯(cuò)誤,接下來通過本文給大家介紹golang反向代理設(shè)置host不生效問題,感興趣的朋友一起看看吧
    2023-05-05
  • Golang中String,rune和byte的相互轉(zhuǎn)換

    Golang中String,rune和byte的相互轉(zhuǎn)換

    Go語言中,string就是只讀的采用utf8編碼的字節(jié)切片,rune是int32的別名,代表字符的Unicode編碼,這篇文章主要介紹了Golang中String,rune和byte的相互轉(zhuǎn)換,感興趣的小伙伴可以了解一下
    2023-10-10
  • Golang實(shí)現(xiàn)Redis事務(wù)深入探究

    Golang實(shí)現(xiàn)Redis事務(wù)深入探究

    這篇文章主要介紹了Golang實(shí)現(xiàn)Redis事務(wù)深入探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • go語言算法題解二叉樹的拷貝、鏡像和對(duì)稱

    go語言算法題解二叉樹的拷貝、鏡像和對(duì)稱

    這篇文章主要為大家詳細(xì)介紹了go語言算法題解二叉樹的拷貝、鏡像和對(duì)稱,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-01-01
  • 我為什么喜歡Go語言(簡潔的Go語言)

    我為什么喜歡Go語言(簡潔的Go語言)

    從2000年至今,也寫了11年代碼了,期間用過VB、Delphi、C#、C++、Ruby、Python,一直在尋找一門符合自己心意和理念的語言。我很在意寫代碼時(shí)的手感和執(zhí)行的效率,所以在Go出現(xiàn)之前一直沒有找到
    2014-10-10
  • Go中Goroutines輕量級(jí)并發(fā)的特性及效率探究

    Go中Goroutines輕量級(jí)并發(fā)的特性及效率探究

    這篇文章主要為大家介紹了Go中Goroutines輕量級(jí)并發(fā)的特性及效率探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • 最新評(píng)論