Golang 字符串连接性能探究
标签(空格分隔): golang
为何探究
几乎所有的软件项目,不管是什么语言,都会用到处理字符串,而拼接字符是最基本,也最常用的。一般连接字符串都有好几种方式,不同的方式适合不同的场景,此次仅探究如果快速动态连接大量的字符串。
相关问题
- https://gocn.io/question/265&sort_key=agree_count&sort=DESC
- http://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go/23857998
探究的代码
还是代码最明了
package main import ( "bytes" "fmt" "strings" "time" ) var way map[int]string func benchmarkStringFunction(n int,index int) (d time.Duration) { v := "ni shuo wo shi bu shi tai wu liao le a?" var s string var buf bytes.Buffer t0 := time.Now() for i := 0; i < n; i++ { switch index { case 0: // fmt.Sprintf s = fmt.Sprintf("%s[%s]",s,v) case 1: // string + s = s + "[" + v + "]" case 2: // strings.Join s = strings.Join([]string{s,"[",v,"]"},"") case 3: // stable bytes.Buffer buf.WriteString("[") buf.WriteString(v) buf.WriteString("]") } } d = time.Since(t0) if index == 3 { s = buf.String() } fmt.Printf("string len: %d\t",len(s)) fmt.Printf("time of [%s]=\t %v\n",way[index],d) return d } func main() { way = make(map[int]string,5) way[0] = "fmt.Sprintf" way[1] = "+" way[2] = "strings.Join" way[3] = "bytes.Buffer" k := 4 d := [5]time.Duration{} for i := 0; i < k; i++ { d[i] = benchmarkStringFunction(10000,i) } }
结果: string len: 410000 time of [fmt.Sprintf]= 426.001476ms string len: 410000 time of [+]= 307.044147ms string len: 410000 time of [strings.Join]= 738.44362ms string len: 410000 time of [bytes.Buffer]= 742.248µs
结果
结果很明显:
- strings.Join 最慢
- fmt.Sprintf 和 string + 差不多
- bytes.Buffer又比上者快约500倍