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

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

标签(空格分隔): Golang


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

  1. 直接用+
  2. strings.Join
  3. strings.Bandle
  4. 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,还是不错的。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值