Created
March 26, 2021 07:19
-
-
Save carthegian/0127ccfa13e17b3028f6d8ace7f7e48e to your computer and use it in GitHub Desktop.
A simple example of benchmarking with Go
This file contains 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 main | |
import ( | |
"bytes" | |
"math/rand" | |
"strings" | |
) | |
func main() { | |
// This main function does nothing since we only want to test benchmarking | |
} | |
func UseConcatOperator(slice []string) string { | |
var s string | |
for _, val := range slice { | |
s = s + val | |
} | |
return s | |
} | |
func UseBytesBuffer(slice []string) string { | |
var b bytes.Buffer | |
for _, val := range slice { | |
b.WriteString(val) | |
} | |
return b.String() | |
} | |
func UseStringsBuilder(slice []string) string { | |
var sb strings.Builder | |
for _, val := range slice { | |
sb.WriteString(val) | |
} | |
return sb.String() | |
} | |
func GetSliceOfStrings() []string { | |
size := 1000 | |
slice := make([]string, size) | |
for i := 0; i < size; i++ { | |
s := "abcdedfghijklmnopqrstuvwxyz" | |
slice[i] = s | |
} | |
return slice | |
} | |
func GetRandomSliceOfStrings() []string { | |
size := 1000 | |
slice := make([]string, size) | |
for i := 0; i < size; i++ { | |
s := GenerateRandomLowercase() | |
slice[i] = s | |
} | |
return slice | |
} | |
func GenerateRandomLowercase() string { | |
// Randomize only lowercase | |
charSet := "abcdedfghijklmnopqrstuvwxyz" | |
var out strings.Builder | |
length := 15 | |
for i := 0; i < length; i++ { | |
random := rand.Intn(len(charSet)) | |
randomChar := charSet[random] | |
out.WriteString(string(randomChar)) | |
} | |
return out.String() | |
} |
This file contains 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 main | |
import ( | |
"testing" | |
) | |
var slice = GetSliceOfStrings() | |
func BenchmarkUseConcatOperator(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
UseConcatOperator(slice) | |
} | |
} | |
func BenchmarkUseBytesBuffer(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
UseBytesBuffer(slice) | |
} | |
} | |
func BenchmarkUseStringsBuilder(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
UseStringsBuilder(slice) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment