go中實(shí)現(xiàn)字符切片和字符串互轉(zhuǎn)
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)文章希望大家以后多多支持腳本之家!
- Golang切片連接成字符串的實(shí)現(xiàn)示例
- Go語言之重要數(shù)組類型切片(slice)make,append函數(shù)解讀
- GO語言中創(chuàng)建切片的三種實(shí)現(xiàn)方式
- golang字符串切片去重的幾種算法
- 詳解golang的切片擴(kuò)容機(jī)制
- 一文詳解Go語言中切片的底層原理
- Go?語言中切片的三種特殊狀態(tài)
- 淺談go中切片比數(shù)組好用在哪
- 一文總結(jié)Go語言切片核心知識(shí)點(diǎn)和坑
- 深入剖析Go語言中數(shù)組和切片的區(qū)別
- Go語言實(shí)戰(zhàn)之切片內(nèi)存優(yōu)化
- Go切片的具體使用
相關(guān)文章
Golang中map的三種聲明定義方式實(shí)現(xiàn)
本文主要介紹了Golang中map的三種聲明定義方式實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02

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

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

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

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

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