golang字符串拼接性能對比


對比 +(運算符)、strings.Join、sprintf、bytes.Buffer對字符串拼接的性能

package main

import (
	"bytes"
	"fmt"
	"strings"
	"testing"
)

func TestfourPlusFour(t *testing.T) {
	fmt.Println("testing")
}

func BenchmarkAddStringWithOperator(b *testing.B) {
	hello := ""
	for i := 0; i < b.N; i++ {
		hello += "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello"
	}
}

func BenchmarkAddStringWithSptint(b *testing.B) {
	hello := ""
	for i := 0; i < b.N; i++ {
		hello = fmt.Sprintf("%s%s", hello, "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello")
	}
}

func BenchmarkAddStringWithJoin(b *testing.B) {
	hello := ""
	for i := 0; i < b.N; i++ {
		hello = strings.Join([]string{hello, "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello"}, "")
	}
}

func BenchmarkAddStringWithBuffer(b *testing.B) {
	var buf bytes.Buffer
	for i := 0; i < b.N; i++ {
		buf.WriteString("hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello")
	}
	_ = buf.String()
}

  運行測試結果:

 

在一些性能要求較高的場合,盡量使用buf.WriteString()以獲得較好的可讀性


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM