[关闭]
@phper 2021-01-27T19:50:06.000000Z 字数 2019 阅读 1545

go里面几个不同的字符串连接符的效率测试

Golang


在搞mysql的orm框架,在处理dsn时候,考虑字符串拼接。有很如下选择:

  1. 直接用+
  2. strings.Join
  3. strings.Bandle
  4. fmt.Sprintf

分别benchmark测试一下,直接上代码跑一下:

  1. func dsnJson (Username string, Password string, Ip string, Port int64, Dbname string) string {
  2. dsn := strings.Join([]string{Username, ":", Password, "@tcp(", Ip, ":", strconv.FormatInt(Port, 10), ")/", Dbname, "?charset=utf8&timeout=5s&readTimeout=6s"}, "")
  3. return dsn
  4. }
  5. func dsnPlus (Username string, Password string, Ip string, Port int64, Dbname string) string {
  6. dsn := Username + ":" + Password + "@tcp(" + Ip + ":" + strconv.FormatInt(Port, 10) + ")/" + Dbname + "?charset=utf8&timeout=5s&readTimeout=6s"
  7. return dsn
  8. }
  9. func dsnSprintf (Username string, Password string, Ip string, Port int64, Dbname string) string {
  10. dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&timeout=5s&readTimeout=6s", Username, Password, Ip, Port, Dbname)
  11. return dsn
  12. }
  13. func dsnBuilder (Username string, Password string, Ip string, Port int64, Dbname string) string {
  14. var dsn2 strings.Builder
  15. dsn2.WriteString(Username)
  16. dsn2.WriteString(":")
  17. dsn2.WriteString(Password)
  18. dsn2.WriteString("@tcp(")
  19. dsn2.WriteString(Ip)
  20. dsn2.WriteString(":")
  21. dsn2.WriteString(strconv.FormatInt(Port, 10))
  22. dsn2.WriteString(")/")
  23. dsn2.WriteString(Dbname)
  24. dsn2.WriteString("?charset=utf8&timeout=5s&readTimeout=6s")
  25. dsn1 := dsn2.String()
  26. dsn2.Reset()
  27. return dsn1
  28. }
  29. func BenchmarkDsnJoin(b *testing.B) {
  30. for i := 0; i < b.N; i++ {
  31. _ = dsnJson("root", "123456", "127.0.0.1", 3306, "ApiDB")
  32. }
  33. }
  34. func BenchmarkDsnPlus(b *testing.B) {
  35. for i := 0; i < b.N; i++ {
  36. _ = dsnPlus("root", "123456", "127.0.0.1", 3306, "ApiDB")
  37. }
  38. }
  39. func BenchmarkDsnBuilder(b *testing.B) {
  40. for i := 0; i < b.N; i++ {
  41. _ = dsnBuilder("root", "123456", "127.0.0.1", 3306, "ApiDB")
  42. }
  43. }
  44. func BenchmarkDsnSprintf(b *testing.B) {
  45. for i := 0; i < b.N; i++ {
  46. _ = dsnSprintf("root", "123456", "127.0.0.1", 3306, "ApiDB")
  47. }
  48. }
  1. $ go test -bench=. -benchmem
  2. BenchmarkDsnJoin-12 8620420 138 ns/op 84 B/op 2 allocs/op
  3. BenchmarkDsnPlus-12 10246611 115 ns/op 84 B/op 2 allocs/op
  4. BenchmarkDsnBuilder-12 5990828 198 ns/op 256 B/op 6 allocs/op
  5. BenchmarkDsnSprintf-12 3582942 337 ns/op 152 B/op 6 allocs/op
  6. PASS
  7. ok command-line-arguments 6.388s

可以看出在少数量的字符拼接的情况下。Join和+的效率是最高的内存分配了2次,每次都是84byte,还是不错的。

所以,在确定字符串个数且很少的情况下,直接用+来拼接字符串吧,效率高又简单方便。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注