go里面几个不同的字符串连接符的效率测试
标签(空格分隔): Golang
在搞mysql的orm框架,在处理dsn时候,考虑字符串拼接。有很如下选择:
- 直接用
+
- strings.Join
- strings.Bandle
- fmt.Sprintf
分别benchmark测试一下,直接上代码跑一下:
func dsnJson (Username string, Password string, Ip string, Port int64, Dbname string) string {
dsn := strings.Join([]string{Username, ":", Password, "@tcp(", Ip, ":", strconv.FormatInt(Port, 10), ")/", Dbname, "?charset=utf8&timeout=5s&readTimeout=6s"}, "")
return dsn
}
func dsnPlus (Username string, Password string, Ip string, Port int64, Dbname string) string {
dsn := Username + ":" + Password + "@tcp(" + Ip + ":" + strconv.FormatInt(Port, 10) + ")/" + Dbname + "?charset=utf8&timeout=5s&readTimeout=6s"
return dsn
}
func dsnSprintf (Username string, Password string, Ip string, Port int64, Dbname string) string {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&timeout=5s&readTimeout=6s", Username, Password, Ip, Port, Dbname)
return dsn
}
func dsnBuilder (Username string, Password string, Ip string, Port int64, Dbname string) string {
var dsn2 strings.Builder
dsn2.WriteString(Username)
dsn2.WriteString(":")
dsn2.WriteString(Password)
dsn2.WriteString("@tcp(")
dsn2.WriteString(Ip)
dsn2.WriteString(":")
dsn2.WriteString(strconv.FormatInt(Port, 10))
dsn2.WriteString(")/")
dsn2.WriteString(Dbname)
dsn2.WriteString("?charset=utf8&timeout=5s&readTimeout=6s")
dsn1 := dsn2.String()
dsn2.Reset()
return dsn1
}
func BenchmarkDsnJoin(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = dsnJson("root", "123456", "127.0.0.1", 3306, "ApiDB")
}
}
func BenchmarkDsnPlus(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = dsnPlus("root", "123456", "127.0.0.1", 3306, "ApiDB")
}
}
func BenchmarkDsnBuilder(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = dsnBuilder("root", "123456", "127.0.0.1", 3306, "ApiDB")
}
}
func BenchmarkDsnSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = dsnSprintf("root", "123456", "127.0.0.1", 3306, "ApiDB")
}
}
$ go test -bench=. -benchmem
BenchmarkDsnJoin-12 8620420 138 ns/op 84 B/op 2 allocs/op
BenchmarkDsnPlus-12 10246611 115 ns/op 84 B/op 2 allocs/op
BenchmarkDsnBuilder-12 5990828 198 ns/op 256 B/op 6 allocs/op
BenchmarkDsnSprintf-12 3582942 337 ns/op 152 B/op 6 allocs/op
PASS
ok command-line-arguments 6.388s
可以看出在少数量的字符拼接的情况下。Join和+
的效率是最高的内存分配了2次,每次都是84byte,还是不错的。
所以,在确定字符串个数且很少的情况下,直接用+
来拼接字符串吧,效率高又简单方便。