Skip to content

Instantly share code, notes, and snippets.

@catatsuy
Created July 15, 2023 07:16
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 catatsuy/c9f593fdcb61604d2150f23b31483bbd to your computer and use it in GitHub Desktop.
Save catatsuy/c9f593fdcb61604d2150f23b31483bbd to your computer and use it in GitHub Desktop.
package bench
import (
"encoding/base64"
"math/rand"
"testing"
"time"
"unsafe"
)
var rd = rand.New(rand.NewSource(time.Now().UnixNano()))
func BenchmarkUseStringCast(b *testing.B) {
for i := 0; i < b.N; i++ {
bb, _ := genByteArray256()
_ = string(bb[0:256])
}
}
func BenchmarkUseUnsafeString(b *testing.B) {
for i := 0; i < b.N; i++ {
bb, _ := genByteArray256()
_ = unsafe.String(&bb[0:256][0], 256)
}
}
func BenchmarkTmpx(b *testing.B) {
for i := 0; i < b.N; i++ {
bb, _ := genByteArray256()
empty(bb)
}
}
func BenchmarkTmpsx(b *testing.B) {
for i := 0; i < b.N; i++ {
bb, _ := genByteArray256()
emptyP(&bb)
}
}
func genByteArray256() (bb [256]byte, err error) {
b := make([]byte, 191)
_, err = rd.Read(b)
if err != nil {
return bb, err
}
dst := make([]byte, base64.StdEncoding.EncodedLen(len(b)))
base64.StdEncoding.Encode(dst, b)
return [256]byte(dst), nil
}
func empty(bb [256]byte) {
_ = bb
}
func emptyP(bb *[256]byte) {
_ = bb
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment