The ways to splice strings are: + , fmt.Sprintf , strings.Builder , bytes.Buffer , strings.Join
+
When using the + operator for splicing, the string will be traversed, calculated and opened up a new space to store the original two strings.
fmt.Sprintf
Due to the use of interface parameters, reflection must be used to obtain values, so there is a performance loss
strings.Builder
Use WriterString() for splicing, the internal implementation is pointer + slice, and String() returns the spliced string, which directly converts []byte to string to avoid copying.
bytes.Buffer
bytes.Buffer is a buffer of byte type, and all the bytes are stored in this buffer .
The bottom layer of bytes.Buffer is also a []byte slice
strings.join
strings.join is also implemented based on strings.builder, and the separator can be customized. The b.Grow(n) method is called in the join method. This is for preliminary capacity allocation, and the length of n calculated earlier is our The length of the slices to be spliced, because the length of the slices we pass in is fixed, so capacity allocation in advance can reduce memory allocation, which is very efficient.
performance comparison
strings.Join = strings.Builder > bytes.Buffer > + > fmt.Sprintf
sample code
func main(){
a := []string{"a", "b", "c"}
//方式1:+
ret := a[0] + a[1] + a[2]
//方式2:fmt.Sprintf
ret := fmt.Sprintf("%s%s%s", a[0],a[1],a[2])
//方式3:strings.Builder
var sb strings.Builder
sb.WriteString(a[0])
sb.WriteString(a[1])
sb.WriteString(a[2])
ret := sb.String()
//方式4:bytes.Buffer
buf := new(bytes.Buffer)
buf.Write(a[0])
buf.Write(a[1])
buf.Write(a[2])
ret := buf.String()
//方式5:strings.Join
ret := strings.Join(a,"")
}