1、字符串+号拼接
+号在拼接字符串上很方便,但性能上确实很慢(+string扩充容量慢),当数量级比较大的时候,性能比Python脚本还慢
package test
import (
"testing"
)
func TestAdd(t *testing.T) {
str := ""
for i := 0; i < 100000; i++ {
str += "add"
}
}
# 测试
go test -v -run TestAdd learn_test.go
=== RUN TestAdd
--- PASS: TestAdd (4.00s)
PASS
ok command-line-arguments 4.006s
比较有效的方法是使用buffer
package test
import (
"testing"
)
func TestBuffer(t *testing.T) {
buff := bytes.NewBufferString("")
for i := 0; i < 100000; i++ {
buff.WriteString("add")
}
}
# 结果
go test -v -run TestBuffer learn_test.go
=== RUN TestBuffer
--- PASS: TestBuffer (0.00s)
PASS
ok command-line-arguments 0.009s
从结果来看效果还是比较明显的
2、使用fmt.Sprintf()来组合字符串(很多的开源代码都是这么写的,但测试发现fmt也是比较慢的)
package test
import (
"testing"
"fmt"
)
func TestFmt(t *testing.T) {
a, b := "add", "test"
for i := 0; i < 1000000; i++ {
fmt.Sprintf("%s%s", a, b)
}
}
# 结果
go test -v -run TestFmt learn_test.go
=== RUN TestFmt
--- PASS: TestFmt (0.25s)
PASS
ok command-line-arguments 0.255s
使用strings.Join后我们在看下性能
package test
import (
"testing"
"strings"
)
func TestJoin(t *testing.T) {
a, b := "add", "test"
for i := 0; i < 1000000; i++ {
strings.Join([]string{a, b}, "")
}
}
# 结果
go test -v -run TestJoin learn_test.go
=== RUN TestJoin
--- PASS: TestJoin (0.06s)
PASS
ok command-line-arguments 0.070s
从结果来看strings.Join比fmt.Sprint快4倍左右