Skip to content

Instantly share code, notes, and snippets.

@superloach
Last active December 31, 2020 23:59
Show Gist options
  • Save superloach/0aa68b4911de53d05e0d75ed085a2fb1 to your computer and use it in GitHub Desktop.
Save superloach/0aa68b4911de53d05e0d75ed085a2fb1 to your computer and use it in GitHub Desktop.
golang bit flag benchmarks

this is a simple test of performance for checking if a uint8 (commonly used for bit flags) is non-zero.

  • u > 0 is the slowest, averaging 1.14ns/op.
  • u != 0 is a little faster, averaging 1.13ns/op.
  • casting u to bool is the fastest, averaging 0.98ns/op.

note: the third method is unsafe, and only confirmed to work on linux/amd64, where a non-zero byte is truthy.

package bitflag_test
const (
Check uint8 = 0b00010000
ValueTrue uint8 = 0b11111111
ValueFalse uint8 = 0b11101111
)
package bitflag_test
import (
"runtime"
"testing"
)
func BenchmarkGtTrue(b *testing.B) {
val := ValueTrue
for i := 0; i < b.N; i++ {
ok := val&Check > 0
runtime.KeepAlive(ok)
}
}
func BenchmarkGtFalse(b *testing.B) {
val := ValueFalse
for i := 0; i < b.N; i++ {
ok := val&Check > 0
runtime.KeepAlive(ok)
}
}
package bitflag_test
import (
"runtime"
"testing"
)
func BenchmarkNeTrue(b *testing.B) {
val := ValueTrue
for i := 0; i < b.N; i++ {
ok := val&Check != 0
runtime.KeepAlive(ok)
}
}
func BenchmarkNeFalse(b *testing.B) {
val := ValueFalse
for i := 0; i < b.N; i++ {
ok := val&Check != 0
runtime.KeepAlive(ok)
}
}
package bitflag_test
import (
"runtime"
"testing"
"unsafe"
)
func BenchmarkUnsafeTrue(b *testing.B) {
val := ValueTrue
for i := 0; i < b.N; i++ {
u := val & Check
ok := *(*bool)(unsafe.Pointer(&u))
runtime.KeepAlive(ok)
}
}
func BenchmarkUnsafeFalse(b *testing.B) {
val := ValueFalse
for i := 0; i < b.N; i++ {
u := val & Check
ok := *(*bool)(unsafe.Pointer(&u))
runtime.KeepAlive(ok)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment