Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement