We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在Go中字符串是原生类型,是只读的,所以用"+"操作符进行字符串时会创建一个新的字符串。如果在循环中使用"+"进行字符串拼接则会创建多个字符串,比如下面这样:
var s string for i := 0; i < 1000; i++ { s += "a" }
那么怎么更高效得进行字符串拼接呢?在早先Go1.10 以前使用的是bytes.Buffer。
Go1.10
bytes.Buffer
package main import ( "bytes" "fmt" ) func main() { var buffer bytes.Buffer for i := 0; i < 1000; i++ { buffer.WriteString("a") } fmt.Println(buffer.String()) }
Go 1.10版本后引入了一个strings.Builder类型,它是这么用的:
Go 1.10
strings.Builder
package main import ( "strings" "fmt" ) func main() { var str strings.Builder for i := 0; i < 10; i++ { str.WriteString("a") } fmt.Println(str.String()) }
会比使用 "+" 或 "+=" 性能高三到四个数量级。
The text was updated successfully, but these errors were encountered:
还有join拼接,这个的也很好
Sorry, something went wrong.
No branches or pull requests
在Go中字符串是原生类型,是只读的,所以用"+"操作符进行字符串时会创建一个新的字符串。如果在循环中使用"+"进行字符串拼接则会创建多个字符串,比如下面这样:
那么怎么更高效得进行字符串拼接呢?在早先
Go1.10
以前使用的是bytes.Buffer
。Go 1.10
版本后引入了一个strings.Builder
类型,它是这么用的:会比使用 "+" 或 "+=" 性能高三到四个数量级。
The text was updated successfully, but these errors were encountered: