1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| package main
import ( "bytes" "fmt" "strings" "time" )
func benchmarkStringFunction(n int, index int) (d time.Duration) { v := "abcd efg hijk lmn" var s string var buf bytes.Buffer
t0 := time.Now() for i := 0; i < n; i++ { switch index { case 0: s = fmt.Sprintf("%s[%s]", s, v) case 1: s = s + "[" + v + "]" case 2: s = strings.Join([]string{s, "[", v, "]"}, "") case 3: b := bytes.Buffer{} b.WriteString("[") b.WriteString(v) b.WriteString("]") s = b.String() case 4: buf.WriteString("[") buf.WriteString(v) buf.WriteString("]") }
if i == n-1 { if index == 4 { s = buf.String() } fmt.Println(len(s)) } } t1 := time.Now() d = t1.Sub(t0) fmt.Printf("time of way(%d)=%v\n", index, d) return d }
func main() { k := 5 d := [5]time.Duration{} for i := 0; i < k; i++ { d[i] = benchmarkStringFunction(10000, i) }
for i := 0; i < k-1; i++ { fmt.Printf("way %d is %6.1f times of way %d\n", i, float32(d[i])/float32(d[k-1]), k-1) } }
|