go拼接字符串性能对比

从测试结果可以看出:
bytes.buffer和builder性能差不多
数组strings.Join性能次之
fmt.Springf性能最差,而且随着字符串越大,性能越差,适合小字符串拼接。

package main

import (
	"bytes"
	"fmt"
	"strings"
	"time"
)

func main() {
	//利用bytes buffer拼接字符串
	var buff bytes.Buffer
	now1 := time.Now()
	for i := 0; i < 100000; i++ {
		buff.WriteString("123456789\n")
	}
	str1 := buff.Bytes()
	fmt.Printf("str1 len:%d\n", len(str1))
	now2 := time.Now()
	fmt.Println("str1 耗时纳秒:")
	fmt.Println(now2.UnixNano() - now1.UnixNano())
	//利用数组append,再strings.Jion拼接字符串
	var arr = make([]string, 100000)
	now1 = time.Now()
	for i := 0; i < 100000; i++ {
		arr = append(arr, "123456789")
	}
	fmt.Printf("str2 len:%d\n", len(strings.Join(arr, "\n")))
	now2 = time.Now()
	fmt.Println("str2 耗时纳秒:")
	fmt.Println(now2.UnixNano() - now1.UnixNano())
	//利用builder拼接字符串
	var build strings.Builder
	now1 = time.Now()
	for i := 0; i < 100000; i++ {
		build.WriteString("123456789\n")
	}
	str3 := build.String()
	fmt.Printf("str3 len:%d\n", len(str3))
	now2 = time.Now()
	fmt.Println("str3 耗时纳秒:")
	fmt.Println(now2.UnixNano() - now1.UnixNano())
	//利用fmt.Sprintf拼接字符串
	var str4 string
	now1 = time.Now()
	for i := 0; i < 100000; i++ {
		str4 = fmt.Sprintf("%s:%s", 123456789, str4)
	}
	fmt.Printf("str4 len:%d\n", len(str4))
	now2 = time.Now()
	fmt.Println("str4 耗时纳秒:")
	fmt.Println(now2.UnixNano() - now1.UnixNano())
}
str1 len:1000000
str1 耗时纳秒:
1667000
str2 len:1099999
str2 耗时纳秒:
13663000
str3 len:1000000
str3 耗时纳秒:
1304000
str4 len:1900000
str4 耗时纳秒:
24963320000

你可能感兴趣的:(go语言,golang,拼接,性能)