Skip to content

Instantly share code, notes, and snippets.

@sjwhitworth
Created April 14, 2019 19:54
Show Gist options
  • Select an option

  • Save sjwhitworth/7c7b22293a3d42cc6efe106577aa71f4 to your computer and use it in GitHub Desktop.

Select an option

Save sjwhitworth/7c7b22293a3d42cc6efe106577aa71f4 to your computer and use it in GitHub Desktop.
Strings vs. bytes
// main.go
package main
import (
"bytes"
"fmt"
"strings"
)
func main() {
q := writeQuery()
s := writeQueryBytes()
fmt.Println(q, s)
}
func writeQuery() string {
s := fmt.Sprintf("%s", strings.Join([]string{"hello", "there"}, ", "))
v := fmt.Sprintf("%s %s", s, strings.Join([]string{"well", "some"}, ", "))
return fmt.Sprintf("%s %s", v, strings.Join([]string{"more", "stuff"}, ", "))
}
func writeQueryBytes() string {
buf := &bytes.Buffer{}
args := []string{"hello", "there", "well", "some", "more", "stuff"}
for i := 0; i < len(args); i++ {
buf.WriteString(args[i])
if i+1 != len(args) {
buf.WriteString(", ")
}
}
return buf.String()
}
// main_test.go
package main
import "testing"
func BenchmarkStringAlloc(b *testing.B) {
for i := 0; i < b.N; i++ {
writeQuery()
}
}
func BenchmarkBytesAlloc(b *testing.B) {
for i := 0; i < b.N; i++ {
writeQueryBytes()
}
}
// 🍎 scratch β†’ gt -bench='.' -benchmem
goos: darwin
goarch: amd64
BenchmarkStringAlloc-8 3000000 469 ns/op 224 B/op 11 allocs/op
BenchmarkBytesAlloc-8 20000000 104 ns/op 112 B/op 2 allocs/op
// 🍎 scratch β†’ go build -gcflags='-m -l' main.go
./main.go:17:37: strings.Join([]string literal, ", ") escapes to heap
./main.go:18:19: s escapes to heap
./main.go:18:43: strings.Join([]string literal, ", ") escapes to heap
./main.go:19:21: v escapes to heap
./main.go:19:45: strings.Join([]string literal, ", ") escapes to heap
./main.go:23:9: writeQueryBytes &bytes.Buffer literal does not escape
./main.go:24:18: writeQueryBytes []string literal does not escape
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment