SHARE
TWEET

Untitled

a guest Apr 24th, 2019 85 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // main.go
  2. package main
  3.  
  4. import (
  5.     "bytes"
  6.     "fmt"
  7.     "strings"
  8. )
  9.  
  10. func main() {
  11.     q := writeQuery()
  12.     s := writeQueryBytes()
  13.  
  14.     fmt.Println(q, s)
  15. }
  16.  
  17. func writeQuery() string {
  18.     s := fmt.Sprintf("%s", strings.Join([]string{"hello", "there"}, ", "))
  19.     v := fmt.Sprintf("%s %s", s, strings.Join([]string{"well", "some"}, ", "))
  20.     return fmt.Sprintf("%s %s", v, strings.Join([]string{"more", "stuff"}, ", "))
  21. }
  22.  
  23. func writeQueryBytes() string {
  24.     buf := &bytes.Buffer{}
  25.     args := []string{"hello", "there", "well", "some", "more", "stuff"}
  26.  
  27.     for i := 0; i < len(args); i++ {
  28.         buf.WriteString(args[i])
  29.         if i+1 != len(args) {
  30.             buf.WriteString(", ")
  31.         }
  32.     }
  33.  
  34.     return buf.String()
  35. }
  36.  
  37. // main_test.go
  38. package main
  39.  
  40. import "testing"
  41.  
  42. func BenchmarkStringAlloc(b *testing.B) {
  43.     for i := 0; i < b.N; i++ {
  44.         writeQuery()
  45.     }
  46. }
  47.  
  48. func BenchmarkBytesAlloc(b *testing.B) {
  49.     for i := 0; i < b.N; i++ {
  50.         writeQueryBytes()
  51.     }
  52. }
  53.  
  54. // 🍎 scratch → gt -bench='.' -benchmem
  55. goos: darwin
  56. goarch: amd64
  57. BenchmarkStringAlloc-8       3000000           469 ns/op         224 B/op         11 allocs/op
  58. BenchmarkBytesAlloc-8       20000000           104 ns/op         112 B/op          2 allocs/op
  59.  
  60. // 🍎 scratch → go build -gcflags='-m -l' main.go
  61. ./main.go:17:37: strings.Join([]string literal, ", ") escapes to heap
  62. ./main.go:18:19: s escapes to heap
  63. ./main.go:18:43: strings.Join([]string literal, ", ") escapes to heap
  64. ./main.go:19:21: v escapes to heap
  65. ./main.go:19:45: strings.Join([]string literal, ", ") escapes to heap
  66. ./main.go:23:9: writeQueryBytes &bytes.Buffer literal does not escape
  67. ./main.go:24:18: writeQueryBytes []string literal does not escape
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top