Skip to content

Instantly share code, notes, and snippets.

@latavin243
Created January 25, 2024 04:05
Show Gist options
  • Save latavin243/b762f18cfc6ffce72cb59a89cf7e4fdf to your computer and use it in GitHub Desktop.
Save latavin243/b762f18cfc6ffce72cb59a89cf7e4fdf to your computer and use it in GitHub Desktop.
go test -bench=. string_test.go
package string_test
import (
"bytes"
"fmt"
"strconv"
"strings"
"testing"
)
const numbers = 100
// fmt.Sprintf
func BenchmarkStringSprintf(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var str string
for j := 0; j < numbers; j++ {
str = fmt.Sprintf("%s%d", str, j)
}
}
b.StopTimer()
}
// add
func BenchmarkStringAdd(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var str string
for j := 0; j < numbers; j++ {
str = str + strconv.Itoa(j)
}
}
b.StopTimer()
}
// bytes.Buffer
func BenchmarkStringBuffer(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var buffer bytes.Buffer
for j := 0; j < numbers; j++ {
buffer.WriteString(strconv.Itoa(j))
}
_ = buffer.String()
}
b.StopTimer()
}
// strings.Builder
func BenchmarkStringBuilder(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var builder strings.Builder
for j := 0; j < numbers; j++ {
builder.WriteString(strconv.Itoa(j))
}
_ = builder.String()
}
b.StopTimer()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment