guanhui07/blog

goalng -字符串高效拼接

Opened this issue · 0 comments

使用 +fmt.Sprintf 的效率是最低的

易用性和性能,一般推荐使用 strings.Builder 来拼接字符串。
Go 官方对 strings.Builder 的解释

A Builder is used to efficiently build a string using Write methods. It minimizes memory copying.

strings.Builder

func builderConcat(n int, str string) string {
	var builder strings.Builder
	for i := 0; i < n; i++ {
		builder.WriteString(str)
	}
	return builder.String()
}