Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fullstop000/1ddef56a05b19d2cd267bd5ea31d904e to your computer and use it in GitHub Desktop.
Save Fullstop000/1ddef56a05b19d2cd267bd5ea31d904e to your computer and use it in GitHub Desktop.
package tt;
import (
"strings"
"testing"
"unsafe"
)
func BenchmarkUnsafePointerVSExplicitlyConvert(b *testing.B) {
s := strings.Repeat("a", 1000)
bytes := []byte(s)
b.Run("str-to-bytes", func(b *testing.B) {
b.Run("unsafe", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = *(*[]byte)(unsafe.Pointer(&s))
}
})
b.Run("normal", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = []byte(s)
}
})
})
b.Run("bytes-to-str", func(b *testing.B) {
b.Run("unsafe", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = *(*string)(unsafe.Pointer(&bytes))
}
})
b.Run("string", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = string(bytes)
}
})
})
}
@Fullstop000
Copy link
Author

BenchmarkUnsafePointerVSExplicitlyConvert/str-to-bytes/unsafe-8         1000000000               0.288 ns/op           0 B/op          0 allocs/op
BenchmarkUnsafePointerVSExplicitlyConvert/str-to-bytes/normal-8          4243749               275 ns/op            1024 B/op          1 allocs/op
BenchmarkUnsafePointerVSExplicitlyConvert/bytes-to-str/unsafe-8         1000000000               0.274 ns/op           0 B/op          0 allocs/op
BenchmarkUnsafePointerVSExplicitlyConvert/bytes-to-str/string-8          4301948               278 ns/op            1024 B/op          1 allocs/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment