码迷,mamicode.com
首页 > 其他好文 > 详细

Go——高效字符串连接

时间:2020-05-25 19:34:46      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:font   port   效率   bytes   str   string   ring   build   一个   

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())
}

 

Go——高效字符串连接

标签:font   port   效率   bytes   str   string   ring   build   一个   

原文地址:https://www.cnblogs.com/coder1013/p/12959429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!