There are actually many implementations of string splicing in golang.
Implementation method
Use operators directly
func BenchmarkAddStringWithOperator(b *) {
hello := "hello"
world := "world"
for i := 0; i < ; i++ {
_ = hello + "," + world
}
}
The strings in golang are immutable. Each operation will produce a new string, so many temporary and useless strings will be generated. Not only will they be useless, but they will also bring additional burden to gc, so the performance is relatively poor.
()
func BenchmarkAddStringWithSprintf(b *) {
hello := "hello"
world := "world"
for i := 0; i < ; i++ {
_ = ("%s,%s", hello, world)
}
}
The internal implementation is implemented using []byte, unlike the direct operator, which produces many temporary strings, but the internal logic is relatively complex, with many additional judgments, and the interface is also used, so the performance is not very good.
()
func BenchmarkAddStringWithJoin(b *) {
hello := "hello"
world := "world"
for i := 0; i < ; i++ {
_ = ([]string{hello, world}, ",")
}
}
Join will calculate the length after splicing based on the content of the string array, and then apply for the corresponding memory size, fill it in one character apart. In the case of an array already, this efficiency will be very high, but it has not been done, so the cost of constructing this data is not small.
()
func BenchmarkAddStringWithBuffer(b *) {
hello := "hello"
world := "world"
for i := 0; i < 1000; i++ {
var buffer
(hello)
(",")
(world)
_ = ()
}
}
This is ideal, it can be used as a variable character, and it also optimizes memory growth. If you can estimate the length of the string, you can also use the () interface to set capacity
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
Main conclusion
- In the event of existing string arrays, using () can have better performance
- In some occasions with high performance requirements, try to use() to obtain better performance
- In the event of low performance requirements, use operators directly, and the code is shorter and clearer, which can achieve better readability.
- If you need to splice not only strings, but also other requirements such as numbers, you can consider ()