Skip to content

Instantly share code, notes, and snippets.

@vbatts
Created September 24, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vbatts/ab17181086aed558dd3a to your computer and use it in GitHub Desktop.
Save vbatts/ab17181086aed558dd3a 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