一.问题描述
今天看gin代码,发现string转[]byte,从1.6开始,做了优化。比[]byte(string) string([]byte) 快6-7倍
// StringToBytes converts string to byte slice without a memory allocation.
func StringToBytes(s string) (b []byte) {
sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len
return b
}
// BytesToString converts byte slice to string without a memory allocation.
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
二.更优的方案
但是发现gin的1.7,又进一步优化,性能更好,比上面又提升了三倍。
// StringToBytes converts string to byte slice without a memory allocation.
func StringToBytes(s string) (b []byte) {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}
最后
以上就是内向项链最近收集整理的关于string转[]byte 高效的方式的全部内容,更多相关string转[]byte内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复