Comparison of several strings together golang

package concat_string

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

const numbers = 100

func BenchmarkSprintf(b *testing.B) {
	b.ResetTimer()
	for index := 0; index < b.N; index++ {
		for i := 0; i < numbers; i++ {
			var s string
			s = fmt.Sprintf("%v%v", s, i)
		}
	}
	b.StopTimer()
}

func BenchmarkStringBuilder(b *testing.B) {
	b.ResetTimer()
	for index := 0; index < b.N; index++ {
		var builder strings.Builder
		for i := 0; i < numbers; i++ {
			builder.WriteString(strconv.Itoa (i)) 
		}
	}
	b.StopTimer()
}

func BechmarkSytesBuf(b *testing.B) {
	b.ResetTimer()
	for index := 0; index < b.N; index++ {
		var buf bytes.Buffer
		for i := 0; i < numbers; i++ {
			buf.WriteString(strconv.Itoa(i))
		}
	}
	b.StopTimer()
}

func BechmarkStringAdd(b *testing.B) {
	b.ResetTimer()
	for index := 0; index < b.N; index++ {
		var s string
		for i := 0; i < numbers; i++ {
			s += strconv.Itoa(i)
		}
	}
	b.StopTimer()
}

 

 

By comparison we found that the best performance string.Builder and bytes.Buffer

Guess you like

Origin www.cnblogs.com/lemonzwt/p/11432537.html