go拼接字符串的方式以及性能比较

原创:golang11/28/2019发布pv:0uv:0ip:0twitter #golang

原文地址:https://www.douyacun.com/article/64bf57a2d3099acbb960ca561d225628

go 拼接数组为字符串的几种方式

  1. + 拼接 最慢 少量比较推荐
  2. strings.join 拼接 其次-推荐
  3. buffers.NewBufferString 拼接 最快,需要自己实现
package main

import (
	"bytes"
	"fmt"
	"strconv"
	"strings"
	"sync"
	"time"
	"unsafe"
)

func main() {
	a := make([]string, 100000)
	for i := 1; i <= 100000; i++ {
		a = append(a, strconv.Itoa(i))
	}
	fmt.Println(unsafe.Sizeof(a))
	wg := sync.WaitGroup{}
	wg.Add(3)
	go plus(&wg, a)
	go join(&wg, a)
	go buffer(&wg, a)
	wg.Wait()
}

func plus(wg *sync.WaitGroup, a []string) {
	defer wg.Done()
	start := time.Now()
	var str string
	for _, i := range a {
		str = str + i
	}
	latency := time.Now().Sub(start)
	fmt.Printf("plus latency: %s len: %d\n", latency, len(str))
}

func join(wg *sync.WaitGroup, a []string) {
	defer wg.Done()
	start := time.Now()
	str := strings.Join(a, "")
	latency := time.Now().Sub(start)
	fmt.Printf("join latency: %s len: %d\n", latency, len(str))
}

func buffer(wg *sync.WaitGroup, a []string) {
	defer wg.Done()
	start := time.Now()
	var str = bytes.NewBufferString("")
	for _, i := range a {
		str.WriteString(i)
	}
	latency := time.Now().Sub(start)
	fmt.Printf("buffer latency: %s len: %d\n", latency, len(str.String()))
}

结果:

24
join latency: 2.536645ms len: 488895
buffer latency: 2.392455ms len: 488895
plus latency: 3.759257148s len: 488895

Process finished with exit code 0
  • 推荐思考一下 fmt.Println(unsafe.Sizeof(a)) 结果为啥是24,了解一下背后的数据结构