高性能转换[]byte 和 string
//这l两个函数是从网上找到的,高频函数使用时性能确实好。原因主要是使用底层指针减少内存 op(内存申请)。
// 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)) }
测试:
func main() { for i := 0; i < 5; i++ { test1() test2() } } func test1() { start := time.Now() str := "" str2 := "" for i := 0; i < 10000000; i++ { str = "hello" + strconv.Itoa(i) s := []byte(str) str2 = string(s) } duration := time.Since(start) fmt.Println("方法一用时:", duration) fmt.Println(str2) } func test2() { start := time.Now() str := "" str2 := "" for i := 0; i < 10000000; i++ { str = "hello" + strconv.Itoa(i) s := StringToBytes(str) str2 = BytesToString(s) } duration := time.Since(start) fmt.Println("方法二用时:", duration) fmt.Println(str2) }
大约 30% 的性能提升