File tree Expand file tree Collapse file tree 2 files changed +14
-10
lines changed
Expand file tree Collapse file tree 2 files changed +14
-10
lines changed Original file line number Diff line number Diff line change 1515
1616package exstrings
1717
18- import (
19- "reflect"
20- "unsafe"
21- )
18+ import "unsafe"
2219
2320/*
2421UnsafeToBytes 把 string 转换为 []byte 没有多余的内存开销。
@@ -63,12 +60,12 @@ UnsafeToBytes 把 string 转换为 []byte 没有多余的内存开销。
6360当然还有更多的使用方法,可以极大的提升我们程序的性能。
6461*/
6562func UnsafeToBytes (s string ) []byte {
66- strHeader := ( * reflect . StringHeader )(unsafe .Pointer (& s ))
67- return * ( * [] byte )( unsafe . Pointer ( & reflect. SliceHeader {
68- Data : strHeader . Data ,
69- Len : strHeader . Len ,
70- Cap : strHeader . Len ,
71- } ))
63+ return * ( * [] byte )(unsafe .Pointer (
64+ & struct {
65+ string
66+ Cap int
67+ }{ s , len ( s )} ,
68+ ))
7269}
7370
7471/*
Original file line number Diff line number Diff line change @@ -64,3 +64,10 @@ func TestBytes(t *testing.T) {
6464 }
6565 }
6666}
67+
68+ func BenchmarkUnsafeToBytes (b * testing.B ) {
69+ str := strings .Repeat ("abc" , 128 )
70+ for i := 0 ; i < b .N ; i ++ {
71+ UnsafeToBytes (str )
72+ }
73+ }
You can’t perform that action at this time.
0 commit comments