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

原创:golang2019/11/28发布pv:1uv:1ip:1twitter #golang

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,了解一下背后的数据结构

相关推荐

  • Go语言高级编程
  • Go并发编程实战(第2版)
  • go面试题:闭包函数指针引用 & 标准输出阻塞
  • go time/rate 接口-账户/IP 限流
  • websocket如何实现统计当前在线人数
  • 微信扫一扫
    关注该公众号