Summary of Golang string concatenation methods

  • 2020-06-19 10:30:18
  • OfStack

String concatenation is actually implemented in many ways in golang.

implementation

Use the operator directly

[

func BenchmarkAddStringWithOperator(b *testing.B) {
hello := "hello"
world := "world"
for i := 0; i < b.N; i++ {
_ = hello + "," + world
}
}

]

The string in golang is immutable, each operation will produce a new string, so many temporary and useless strings will be generated, which is not only useless, but also brings extra burden to gc, so the performance is poor

[

fmt.Sprintf()
func BenchmarkAddStringWithSprintf(b *testing.B) {
hello := "hello"
world := "world"
for i := 0; i < b.N; i++ {
_ = fmt.Sprintf("%s,%s", hello, world)
}
}

]

The []byte implementation is implemented internally, unlike the direct operator, which produces a lot of temporary strings, but the internal logic is more complex, with a lot of extra judgment, and interface is used, so performance is not very good

[

strings.Join()
func BenchmarkAddStringWithJoin(b *testing.B) {
hello := "hello"
world := "world"
for i := 0; i < b.N; i++ {
_ = strings.Join([]string{hello, world}, ",")
}
}

]

join will calculate the length after concatenation according to the contents of the string array, and then apply for the corresponding size of memory, filling in each character. In the case that there is already one array, this efficiency will be high, but it is not available, and the cost of constructing this data is not small

[

buffer.WriteString()
func BenchmarkAddStringWithBuffer(b *testing.B) {
hello := "hello"
world := "world"
for i := 0; i < 1000; i++ {
var buffer bytes.Buffer
buffer.WriteString(hello)
buffer.WriteString(",")
buffer.WriteString(world)
_ = buffer.String()
}
}

]

This is ideal for mutable characters, optimized for memory growth, and can be set using the ES114en.Grow () interface if you can estimate the length of the string

The test results

[

BenchmarkAddStringWithOperator-8 50000000 30.3 ns/op
BenchmarkAddStringWithSprintf-8 5000000 261 ns/op
BenchmarkAddStringWithJoin-8 30000000 58.7 ns/op
BenchmarkAddStringWithBuffer-8 2000000000 0.00 ns/op

]

The main conclusion

strings. Join() gives better performance where there are already string arrays Use buffer.WriteString () for better performance in more demanding situations When performance requirements are not too high, use operators directly, the code is shorter and clearer, can get better readability fmt. Sprintf() if you need to concatenate not just strings but other requirements such as Numbers

Related articles: