Creating a new bytes reader with each function call is inefficient as it requires a lot of allocations and performs a lot of operations.
The needed numeric types can be retrieved simply by utilizing bitwise operations.
This approach is good in performance and the code looks simpler and cleaner.
I ran benchmarks on the Bits24ToIntReader function and the provided optimized.
Here are my results:
func Bits24ToIntReader(b []byte) int {
if len(b) != 3 {
panic("Expected size 3!")
}
// add some padding to turn a 24-bit integer into a 32-bit integer
b = append([]byte{0x00}, b...)
var payload int32
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.LittleEndian, &payload)
if err != nil {
// TODO: make safe
panic(err)
}
return int(payload) // easier to work with ints
}
Creating a new bytes reader with each function call is inefficient as it requires a lot of allocations and performs a lot of operations. The needed numeric types can be retrieved simply by utilizing bitwise operations. This approach is good in performance and the code looks simpler and cleaner.
I ran benchmarks on the
Bits24ToIntReader
function and the provided optimized. Here are my results:And here are the functions that I benchmarked:
Original, with the use of
bytes.NewReader
Bitwise operations,
shift
andor
Unsafe cast (but should be safe since we check whether the sufficient number of elements is present, right?)