Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2025-02-01 - Zero-Alloc Patterns
**Learning:** Parsing IP addresses from strings/bytes (like in `/proc/net/tcp`) using `make([]byte, ...)` creates significant pressure on the GC in hot paths. Using stack-allocated arrays `[16]byte` and decoding directly into them eliminates these allocations entirely.
**Action:** Always prefer `[N]byte` over `make([]byte, N)` for small, fixed-size buffers in parsing loops, especially for IP addresses and ports.
23 changes: 13 additions & 10 deletions proc/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"bytes"
"encoding/binary"
"encoding/hex"
"net"
"os"

"inet.af/netaddr"
Expand Down Expand Up @@ -93,24 +92,28 @@ func decodeAddr(src []byte) netaddr.IPPort {
if col == -1 || (col != 8 && col != 32) {
return netaddr.IPPort{}
}
ip := make([]byte, col/2)
if _, err := hex.Decode(ip, src[:col]); err != nil {

// Parsing to stack-allocated buffers to avoid heap allocations
var ip [16]byte
if _, err := hex.Decode(ip[:col/2], src[:col]); err != nil {
return netaddr.IPPort{}
}
port := make([]byte, 2)
if _, err := hex.Decode(port, src[col+1:]); err != nil {
var portBuf [2]byte
if _, err := hex.Decode(portBuf[:], src[col+1:]); err != nil {
return netaddr.IPPort{}
}

var v uint32
for i := 0; i < len(ip); i += 4 {
for i := 0; i < col/2; i += 4 {
v = binary.BigEndian.Uint32(ip[i : i+4])
binary.LittleEndian.PutUint32(ip[i:i+4], v)
}
Comment on lines 106 to 110

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For clarity and potentially a minor performance improvement, you can perform the byte-swapping directly. This makes the 4-byte reversal explicit and removes the need for the temporary variable v.

Suggested change
var v uint32
for i := 0; i < len(ip); i += 4 {
for i := 0; i < col/2; i += 4 {
v = binary.BigEndian.Uint32(ip[i : i+4])
binary.LittleEndian.PutUint32(ip[i:i+4], v)
}
// The IP address in /proc/net/tcp* is in little-endian format for each 32-bit word.
// We need to swap the byte order of each word to get the standard big-endian representation.
for i := 0; i < col/2; i += 4 {
ip[i], ip[i+1], ip[i+2], ip[i+3] = ip[i+3], ip[i+2], ip[i+1], ip[i]
}


ipp, ok := netaddr.FromStdIP(net.IP(ip))
if !ok {
return netaddr.IPPort{}
var ipp netaddr.IP
if col == 8 {
ipp = netaddr.IPv4(ip[0], ip[1], ip[2], ip[3])
} else {
ipp = netaddr.IPFrom16(ip)
}
return netaddr.IPPortFrom(ipp, binary.BigEndian.Uint16(port))
return netaddr.IPPortFrom(ipp, binary.BigEndian.Uint16(portBuf[:]))
}
Loading