【Go学习】string连接效率比较

string连接效率比较

方法

  1. +=
  2. fmt.Springf
  3. buffer.WriteString
  4. builder.WriteString
  5. append

代码

func main() {
	// 1. +=
	str := "test"
	name := "zh"
	s := time.Now()
	for i := 0; i < 100000; i++ {
		str += name
	}
	e := time.Since(s)
	fmt.Println("+=: time cost:", e)

	// 2. fmt.Sprintf
	str = "test"
	name = "zh"
	s = time.Now()
	for i := 0; i < 100000; i++ {
		str = fmt.Sprintf("%s%s", str, name)
	}
	e = time.Since(s)
	fmt.Println("fmt.Sprintf time cost:", e)

	// 3.  buffer.WriteString
	str = "test"
	name = "zh"
	var buffer = bytes.Buffer{}
	s = time.Now()
	buffer.WriteString(str)
	for i := 0; i < 100000; i++ {
		buffer.WriteString(name)
	}
	e = time.Since(s)
	fmt.Println("buffer.WriteString time cost:", e)

	// 4. builder.WriteString
	str = "test"
	name = "zh"
	var builder = strings.Builder{}
	s = time.Now()
	builder.WriteString(str)
	for i := 0; i < 100000; i++ {
		builder.WriteString(name)
	}
	e = time.Since(s)
	fmt.Println("builder.WriteString time cost:", e)

	// 5. append
	str = "test"
	name = "zh"
	s = time.Now()
	bstr := []byte(str)
	bname := []byte(name)
	for i := 0; i < 100000; i++ {
		bstr = append(bstr, bname...)
	}
	e = time.Since(s)
	fmt.Println("append time cost:", e)
}

结果

+=: time cost: 1.3233293s
fmt.Sprintf time cost: 2.6775514s
buffer.WriteString time cost: 519.2µs
builder.WriteString time cost: 518.1µs
append time cost: 503.6µs

总结
以上结果是在自己电脑上跑的,仅供参考

append, strings.builder 效率高

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值