Keith made me aware of the fact that my benchmark is using the
binary.BigEndian interface instead of "unrolling" the interface to use the
specific type at runtime.
cpu: Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz
BenchmarkUnsafe-8 10 5.991 ns/op 0
B/op
Keith, thank you very much for your feedback, it is highly appreciated!
With this in mind, it's time for lies, more lies, and statistics,
benchmarking the three different implementations below:
func (r *Reader) Uint32() uint32 {
if r.err != nil {
return 0
}
var s struct {
_ [0]uint32
b [4]byte
If you're using unsafe anyway, I'd go the other direction, casting from the
larger alignment to the smaller one. That avoids any alignment concerns.
var x uint32
b := (*[4]byte)(unsafe.Pointer())[:]
r.buff.Read(b)
return x
I would encourage you to use encoding/binary though. It all works out