Skip to content
New issue

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

高性能地拼接字符串 #68

Open
kevinyan815 opened this issue Oct 11, 2021 · 1 comment
Open

高性能地拼接字符串 #68

kevinyan815 opened this issue Oct 11, 2021 · 1 comment

Comments

@kevinyan815
Copy link
Owner

在Go中字符串是原生类型,是只读的,所以用"+"操作符进行字符串时会创建一个新的字符串。如果在循环中使用"+"进行字符串拼接则会创建多个字符串,比如下面这样:

var s string
for i := 0; i < 1000; i++ {
    s += "a"
}

那么怎么更高效得进行字符串拼接呢?在早先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类型,它是这么用的:

package main

import (
    "strings"
    "fmt"
)

func main() {
    var str strings.Builder

    for i := 0; i < 10; i++ {
        str.WriteString("a")
    }

    fmt.Println(str.String())
}

会比使用 "+" 或 "+=" 性能高三到四个数量级。

@Talent-hu
Copy link

还有join拼接,这个的也很好

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants