golang-字符串拼接性能对比

下面代码,分别比较了 fmt.Sprintf,string +,strings.Join,bytes.Buffer,方法是循环若干次比较总时间。

性能由高到低依次是(bytes.Buffer) > (string +) > (fmt.Sprintf) > strings.Join

测试代码如下:

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: // fmt.Sprintf
            s = fmt.Sprintf("%s[%s]", s, v)
        case 1: // string +
            s = s + "[" + v + "]"
        case 2: // strings.Join
            s = strings.Join([]string{s, "[", v, "]"}, "")
        case 3: // temporary bytes.Buffer
            b := bytes.Buffer{}
            b.WriteString("[")
            b.WriteString(v)
            b.WriteString("]")
            s = b.String()
        case 4: // stable bytes.Buffer
            buf.WriteString("[")
            buf.WriteString(v)
            buf.WriteString("]")
        }

        if i == n-1 {
            if index == 4 { // for stable bytes.Buffer
                s = buf.String()
            }
            fmt.Println(len(s)) // consume s to avoid compiler optimization
        }
    }
    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)
    }
}

结果:

410000
time of way(0)=697.113743ms
410000
time of way(1)=455.614054ms
410000
time of way(2)=1.08289487s
41
time of way(3)=2.154884ms
410000
time of way(4)=792.74µs
way 0 is  879.4 times of way 4
way 1 is  574.7 times of way 4
way 2 is 1366.0 times of way 4
way 3 is    2.7 times of way 4

猜你喜欢

转载自blog.csdn.net/gongpulin/article/details/80408091