binary: append slices

A new optimization in Go 1.11 improves the efficiency of slice extension:
"The compiler now optimizes slice extension of the form append(s, make([]T, n)...)."
https://tip.golang.org/doc/go1.11#performance-compiler

Before:
BenchmarkMarshalUnmarshal-12    	 2000000	       664 ns/op	       0 B/op	       0 allocs/op
BenchmarkReadWrite-12           	  500000	      2395 ns/op	     304 B/op	      24 allocs/op

After:
BenchmarkMarshalUnmarshal-12    	 2000000	       628 ns/op	       0 B/op	       0 allocs/op
BenchmarkReadWrite-12           	  500000	      2411 ns/op	     304 B/op	      24 allocs/op

BenchmarkMarshalUnmarshal benchmarks the code in this package, BenchmarkReadWrite benchmarks the code in the standard library.

PiperOrigin-RevId: 209679979
Change-Id: I51c6302e53f60bf79f84576b1ead4d36658897cb
This commit is contained in:
Ian Gudger
2018-08-21 16:26:32 -07:00
committed by Shentubot
parent ae68e9e751
commit e29a02239e
+3 -10
View File
@@ -35,21 +35,21 @@ var BigEndian = binary.BigEndian
// AppendUint16 appends the binary representation of a uint16 to buf.
func AppendUint16(buf []byte, order binary.ByteOrder, num uint16) []byte {
buf = extendZero(2, buf)
buf = append(buf, make([]byte, 2)...)
order.PutUint16(buf[len(buf)-2:], num)
return buf
}
// AppendUint32 appends the binary representation of a uint32 to buf.
func AppendUint32(buf []byte, order binary.ByteOrder, num uint32) []byte {
buf = extendZero(4, buf)
buf = append(buf, make([]byte, 4)...)
order.PutUint32(buf[len(buf)-4:], num)
return buf
}
// AppendUint64 appends the binary representation of a uint64 to buf.
func AppendUint64(buf []byte, order binary.ByteOrder, num uint64) []byte {
buf = extendZero(8, buf)
buf = append(buf, make([]byte, 8)...)
order.PutUint64(buf[len(buf)-8:], num)
return buf
}
@@ -204,13 +204,6 @@ func sizeof(data reflect.Value) uintptr {
}
}
func extendZero(amount uintptr, buf []byte) []byte {
for i := uintptr(0); i < amount; i++ {
buf = append(buf, 0)
}
return buf
}
// ReadUint16 reads a uint16 from r.
func ReadUint16(r io.Reader, order binary.ByteOrder) (uint16, error) {
buf := make([]byte, 2)