github.com/iainanderson83/datastructures@v0.0.4-0.20191103204413-889e20b53bcf/arrays/slice_size_test.go (about) 1 package main 2 3 import ( 4 "strconv" 5 "testing" 6 ) 7 8 func numbersToStringsBad(numbers []int) []string { 9 vals := []string{} 10 for _, n := range numbers { 11 vals = append(vals, strconv.Itoa(n)) 12 } 13 return vals 14 } 15 16 func numbersToStringsBetter(numbers []int) []string { 17 vals := make([]string, 0, len(numbers)) 18 for _, n := range numbers { 19 vals = append(vals, strconv.Itoa(n)) 20 } 21 return vals 22 } 23 24 func numbersToStringsBest(numbers []int) []string { 25 vals := make([]string, len(numbers)) 26 for i, n := range numbers { 27 vals[i] = strconv.Itoa(n) 28 } 29 return vals 30 } 31 32 func BenchmarkSliceConversion(b *testing.B) { 33 numbers := make([]int, 100) 34 for i := range numbers { 35 numbers[i] = i 36 } 37 38 b.Run("bad", func(b *testing.B) { 39 b.ReportAllocs() 40 for i := 0; i < b.N; i++ { 41 numbersToStringsBad(numbers) 42 } 43 }) 44 45 b.Run("better", func(b *testing.B) { 46 b.ReportAllocs() 47 for i := 0; i < b.N; i++ { 48 numbersToStringsBetter(numbers) 49 } 50 }) 51 52 b.Run("best", func(b *testing.B) { 53 b.ReportAllocs() 54 for i := 0; i < b.N; i++ { 55 numbersToStringsBest(numbers) 56 } 57 }) 58 }