Skip to content

Instantly share code, notes, and snippets.

@robbinhan
Forked from vbatts/README.md
Created January 7, 2021 07:26
Show Gist options
  • Save robbinhan/5759fc63afc2e7165b1f3d02d5bffc0e to your computer and use it in GitHub Desktop.
Save robbinhan/5759fc63afc2e7165b1f3d02d5bffc0e to your computer and use it in GitHub Desktop.
`fmt.Sprintf("%s", buf)` vs `string(buf)` for simple []byte arrays

Curiosity on the differences from moby/moby#16531 (comment)

$ go test
PASS
ok      _/home/vbatts/tmp/string        0.003s
$ go test -run=NONE -bench=. -test.benchmem=true 
PASS
BenchmarkString-4         100000             18982 ns/op               0 B/op          0 allocs/op
BenchmarkFmt-4              5000            248974 ns/op           48012 B/op       2000 allocs/op
ok      _/home/vbatts/tmp/string        3.369s
package str
import (
"crypto/rand"
"fmt"
"log"
"testing"
)
var randoList [1000][]byte
func init() {
for i := 0; i < 1000; i++ {
buf := make([]byte, 5)
if _, err := rand.Read(buf); err != nil {
log.Fatalf("failed init: %s", err)
}
randoList[i] = buf
}
}
func TestFormatting(t *testing.T) {
for i, blob := range randoList {
formatFmt := fmt.Sprintf("%s", blob)
formatStr := string(blob)
if formatFmt != formatStr {
t.Errorf("%d: %q and %q do not match", i, formatFmt, formatStr)
}
}
}
func BenchmarkString(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, blob := range randoList {
_ = string(blob)
}
}
}
func BenchmarkFmt(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, blob := range randoList {
_ = fmt.Sprintf("%s", blob)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment