Go的字符串连接的几种方法和优化

主要参考文章

[https://segmentfault.com/a/1190000012978989]:

Go的字符串连接的几种方法和优化

运算符+

Go和Java一样,string是不可变的,因此频繁使用+性能不好。

bytes.buffer

var buffer bytes.buffer
buffer.WriteString("Hello")
buffer.Write([]byte(", World!"))

相当于Java的StringBuffer,用法类似。http://docscn.studygolang.com/pkg/bytes/#Buffer

fmt.Sprintf()

最通用的字符串输出方式,缺点是内部逻辑复杂,只适用于一次输出的某些场景使用。

strings.Join()

内部会申请好需要的总长度,在已有切片的基础上性能不错。

猜你喜欢

转载自www.cnblogs.com/roastpiglet/p/12960414.html