blog.farhan.codes

Farhan's Personal and Professional Blog


Benchmarking Base32 vs Base64

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:

package main

func main() {
}

I ran both as follows:

goos: linux
goarch: amd64
pkg: baserace
cpu: 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz
BenchmarkBase32Run-8   	    5502	    185708 ns/op
BenchmarkBase64Run-8   	    8196	    147614 ns/op
PASS
ok  	baserace	3.255s

The results are not properly labeled, but in short Base64 ran 8196 times and ran each loop at 147614 nanoseconds, whereas base32 ran 5502 times at 185708 nanoseconds per iteration. Clearly Base64 is significantly faster.

Without looking at the inner workings of either, I did not expect this.