Skip to content

Commit 5bec363

Browse files
committed
pgio: optimize append/set functions with direct byte shifts
Replace zero-fill + overwrite pattern with direct byte appends. Use array pointer cast in SetInt32 to eliminate bounds checks. Benchmarks show 12-19% improvement in message building: BindMessage5Params: 164 ns → 132 ns (19% faster) BindMessage20Params: 922 ns → 780 ns (15% faster) Simulate10kQueries: 1.37ms → 1.21ms (12% faster) Assembly comparison for SetInt32: Before: 134 bytes, 4 bounds checks, 4 panicIndex calls After: 63 bytes, 1 bounds check, 1 panicSliceConvert call No functional changes. All existing tests pass.
1 parent 9e3a3ad commit 5bec363

1 file changed

Lines changed: 7 additions & 15 deletions

File tree

internal/pgio/write.go

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,18 @@
11
package pgio
22

3-
import "encoding/binary"
4-
53
func AppendUint16(buf []byte, n uint16) []byte {
6-
wp := len(buf)
7-
buf = append(buf, 0, 0)
8-
binary.BigEndian.PutUint16(buf[wp:], n)
9-
return buf
4+
return append(buf, byte(n>>8), byte(n))
105
}
116

127
func AppendUint32(buf []byte, n uint32) []byte {
13-
wp := len(buf)
14-
buf = append(buf, 0, 0, 0, 0)
15-
binary.BigEndian.PutUint32(buf[wp:], n)
16-
return buf
8+
return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
179
}
1810

1911
func AppendUint64(buf []byte, n uint64) []byte {
20-
wp := len(buf)
21-
buf = append(buf, 0, 0, 0, 0, 0, 0, 0, 0)
22-
binary.BigEndian.PutUint64(buf[wp:], n)
23-
return buf
12+
return append(buf,
13+
byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32),
14+
byte(n>>24), byte(n>>16), byte(n>>8), byte(n),
15+
)
2416
}
2517

2618
func AppendInt16(buf []byte, n int16) []byte {
@@ -36,5 +28,5 @@ func AppendInt64(buf []byte, n int64) []byte {
3628
}
3729

3830
func SetInt32(buf []byte, n int32) {
39-
binary.BigEndian.PutUint32(buf, uint32(n))
31+
*(*[4]byte)(buf) = [4]byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)}
4032
}

0 commit comments

Comments
 (0)