This is a very rudimentary benchmark of Base32 vs Base64 performance in Golang. This should also serve as an example of Golang’s benchmarking toolchain. Conclusion: Base64 is faster.
This code works by creating 1000 test strings, then performing Base32 and Base64 conversions. Timing is done by Go’s built-in benchmarking tooling, which is part of the testing framework. Here is the code:
package main
import "os"
import "time"
import "testing"
import "math/rand"
import "encoding/base32"
import "encoding/base64"
var strings = []string{}
func setupStrings(n int) []string {
charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
strings := []string{}
rand.Seed(time.Now().UnixNano())
for i := 0; i < n; i++ {
newstring := genRandomString(charset, 32)
strings = append(strings, newstring)
}
return strings
}
func genRandomString(charset string, length int) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
}
return string(b)
}
func setup() {
strings = setupStrings(1000)
}
func BenchmarkBase32Run(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, s := range strings {
_ = base32.StdEncoding.EncodeToString([]byte(s))
}
}
}
func BenchmarkBase64Run(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, s := range strings {
_ = base64.StdEncoding.EncodeToString([]byte(s))
}
}
}
func TestMain(m *testing.M) {
setup()
code := m.Run()
os.Exit(code)
}
You will also need a main function, mine is as follows:
Read more...