Skip to content

Commit

Permalink
Merge pull request #11 from openset/master
Browse files Browse the repository at this point in the history
Update: UnsafeToBytes
  • Loading branch information
thinkeridea authored Jan 6, 2020
2 parents 64bce00 + acc8668 commit 5b54d82
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
17 changes: 7 additions & 10 deletions exstrings/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@

package exstrings

import (
"reflect"
"unsafe"
)
import "unsafe"

/*
UnsafeToBytes 把 string 转换为 []byte 没有多余的内存开销。
Expand Down Expand Up @@ -63,12 +60,12 @@ UnsafeToBytes 把 string 转换为 []byte 没有多余的内存开销。
当然还有更多的使用方法,可以极大的提升我们程序的性能。
*/
func UnsafeToBytes(s string) []byte {
strHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: strHeader.Data,
Len: strHeader.Len,
Cap: strHeader.Len,
}))
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}

/*
Expand Down
7 changes: 7 additions & 0 deletions exstrings/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,10 @@ func TestBytes(t *testing.T) {
}
}
}

func BenchmarkUnsafeToBytes(b *testing.B) {
str := strings.Repeat("abc", 128)
for i := 0; i < b.N; i++ {
UnsafeToBytes(str)
}
}

0 comments on commit 5b54d82

Please sign in to comment.