Skip to content

Instantly share code, notes, and snippets.

@x893675
Last active September 10, 2020 10:02
Show Gist options
  • Save x893675/8291d365487c5438769657a65ae94f81 to your computer and use it in GitHub Desktop.
Save x893675/8291d365487c5438769657a65ae94f81 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"unsafe"
)
type StringHeader struct {
Data uintptr
Len int
}
type SliceHeader struct {
Data uintptr
Len int
Cap int
}
func string2bytes(s string) []byte {
//stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
//bh := reflect.SliceHeader{
// Data: stringHeader.Data,
// Len: stringHeader.Len,
// Cap: stringHeader.Len,
//}
x := (*[2]uintptr)(unsafe.Pointer(&s))
h := [3]uintptr{x[0], x[1], x[1]}
return *(*[]byte)(unsafe.Pointer(&h))
}
func bytes2string(b []byte) string {
//sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
//sh := reflect.StringHeader{
// Data: sliceHeader.Data,
// Len: sliceHeader.Len,
//}
return *(*string)(unsafe.Pointer(&b))
}
func main() {
fmt.Println(string2bytes("hello"))
}
package main
import (
"strings"
"testing"
)
var s = strings.Repeat("a", 1024)
func test() {
b := []byte(s)
_ = string(b)
}
func test2() {
b := string2bytes(s)
_ = bytes2string(b)
}
func BenchmarkTest(b *testing.B) {
for i := 0; i < b.N; i++ {
test()
}
}
func BenchmarkTestBlock(b *testing.B) {
for i := 0; i < b.N; i++ {
test2()
}
}
//go test -v -bench . -benchmem
//goos: darwin
//goarch: amd64
//BenchmarkTest
//BenchmarkTest-12 4438213 270 ns/op 2048 B/op 2 allocs/op
//BenchmarkTestBlock
//BenchmarkTestBlock-12 1000000000 0.500 ns/op 0 B/op 0 allocs/op
//PASS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment