Created
January 25, 2024 04:05
-
-
Save arvin243/b762f18cfc6ffce72cb59a89cf7e4fdf to your computer and use it in GitHub Desktop.
go test -bench=. string_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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