Go基础——高效字符串连接

Go中可以使用“+”合并字符串,但是这种合并方式效率非常低,每合并一次,都是创建一个新的字符串,就必须遍历复制一次字符串

建议:

  • 1.10 之前版本使用 bytes.Buffer
  • 1.10+ 以后版本使用 strings.Builder(Go1.10以后出现的)
package main
 
import (
    "fmt"
    "strings"
)
 
func main() {
    ss := []string{
        "sh",
        "hn",
        "test",
    }
 
    var b strings.Builder
    for _, s := range ss {
        fmt.Fprint(&b, s)
    }
 
    print(b.String())
}

猜你喜欢

转载自www.cnblogs.com/gjh99/p/12123147.html