Skip to content

Commit 5b54d82

Browse files
authored
Merge pull request #11 from openset/master
Update: UnsafeToBytes
2 parents 64bce00 + acc8668 commit 5b54d82

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

exstrings/convert.go

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,7 @@
1515

1616
package exstrings
1717

18-
import (
19-
"reflect"
20-
"unsafe"
21-
)
18+
import "unsafe"
2219

2320
/*
2421
UnsafeToBytes 把 string 转换为 []byte 没有多余的内存开销。
@@ -63,12 +60,12 @@ UnsafeToBytes 把 string 转换为 []byte 没有多余的内存开销。
6360
当然还有更多的使用方法,可以极大的提升我们程序的性能。
6461
*/
6562
func 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
/*

exstrings/convert_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
}

0 commit comments

Comments
 (0)