koko
koko copied to clipboard
Optimize memory allocation with buffer pools and slice reuse
Addresses potential memory issues by reducing allocations in hot paths through buffer pooling and capacity-aware buffer management.
Changes
Buffer Pool Infrastructure (pkg/utils/buffer.go)
- Added
BufferPooltype wrappingsync.Poolwith configurable sizes - Global pools:
SmallBufferPool(1KB),MediumBufferPool(32KB),LargeBufferPool(64KB) -
BytesBufferPoolforbytes.Bufferreuse withGetBytesBuffer()/PutBytesBuffer()helpers
FTP File Operations (pkg/proxy/recorder.go)
- Pool-based 32KB buffer reuse in
FTPFileInfo.WriteFromReader()instead of per-call allocation
Zmodem Parsing (pkg/zmodem/zsession.go)
- Reuse
parsedSubPacketslice capacity vias.parsedSubPacket = s.parsedSubPacket[:0] - Reset
subPacketBufwhen capacity exceeds 64KB to prevent memory bloat
Terminal Parser (pkg/proxy/parsercmd.go)
- Added
resetInputBuf()to reset buffers and reclaim memory when capacity exceeds threshold
Example
// Before: allocates 32KB per call
buf := make([]byte, 32*1024)
// After: reuses pooled buffer
bufPtr := ftpReadBufferPool.Get().(*[]byte)
buf := *bufPtr
defer ftpReadBufferPool.Put(bufPtr)
Benchmarks
BenchmarkBytesBufferPoolGet 0 B/op 0 allocs/op
BenchmarkRawBytesBufferAlloc 64 B/op 1 allocs/op
Original prompt
分析可能存在的内存问题,优化内存分配
💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.
Quality Gate passed
Issues
12 New issues
0 Accepted issues
Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code