golang中字符串拼接方法

  1. +=
  2. fmt.sprintf
  3. append
  4. buffer.WriteString
  5. copy

废话不多说,直接上代码看效果

package main

import (
    "bytes"
    "fmt"
    "time"
)

func main() {
    str:="chinese"
    city:="beijing"
    
    // 1. +=
    s:=time.Now()
    for i:=0;i<100000;i++ {
        str +=city
    }
    e:=time.Since(s)
    fmt.Println("time cost 1:", e)
  
    // 2. fmt.Sprintf
    str="chinese"
    city="beijing"
    s=time.Now()
    for i:=0;i<100000;i++ {
        str = fmt.Sprintf("%s%s",str,city)
    }
    e=time.Since(s)
    fmt.Println("time cost 2:", e)
  
     //3.  buffer.WriteString
    str="chinese"
    city="beijing"
    s=time.Now()
    var buf= bytes.Buffer{}
    buf.WriteString(str)
    for i:=0;i<100000;i++ {
        buf.WriteString(city)
    }
    e=time.Since(s)
    fmt.Println("time cost 3:", e)

   //4. append
    str="chinese"
    city="beijing"
    s=time.Now()
    bstr:=[]byte(str)
    bcity:=[]byte(city)
    for i:=0;i<100000;i++ {
        bstr= append(bstr, bcity...)
    }
    e=time.Since(s)
    fmt.Println("time cost 4:", e)

  // 5. copy
    str="chinese"
    city="beijing"
    s=time.Now()
    zstr :=[]byte(str)
    for i:=0;i<100000;i++ {
        copy(zstr, city)
    }
    e=time.Since(s)
    fmt.Println("time cost 5:", e)
}

最终效果(多次尝试,对比结果都一致):

time cost 1: 3.176250251s
time cost 2: 5.347827717s
time cost 3: 1.051104ms
time cost 4: 769.258µs
time cost 5: 323.968µs

效率:copy > append > buf.WriteString > += > fmt.Sprintf

所以请慎用fmt.Sprinf 和 +=