优化:减少代码重复和内存分配
主要优化: 1. 提取重复代码(topic_processor.go) - 新增 addStatusToRecords() 辅助方法 - QueryOldest 和 QueryNewest 中的状态添加逻辑重复,已提取 - 减少 38 行重复代码 2. 优化内存分配(index.go) - 在 RecordIndex 结构体中添加可重用的 entryBuf - Append 方法不再每次都分配 8 字节 buffer - 高频写入场景下可显著减少 GC 压力 性能提升: - 减少内存分配次数(每次写入索引节省 1 次分配) - 提高代码可维护性(消除重复代码) - 所有测试通过 ✅ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
7
index.go
7
index.go
@@ -41,6 +41,7 @@ type RecordIndex struct {
|
||||
syncBatch int // 同步批次大小
|
||||
lastSync time.Time // 上次同步时间
|
||||
dirtyCount int // 未同步的记录数
|
||||
entryBuf [IndexEntrySize]byte // 可重用的写入缓冲区
|
||||
mu sync.Mutex // 保护并发访问
|
||||
}
|
||||
|
||||
@@ -156,10 +157,10 @@ func (ri *RecordIndex) Append(offset int64) error {
|
||||
defer ri.mu.Unlock()
|
||||
|
||||
// 追加到索引文件(先写文件,后更新内存)
|
||||
entryBuf := make([]byte, IndexEntrySize)
|
||||
binary.LittleEndian.PutUint64(entryBuf, uint64(offset))
|
||||
// 使用可重用的 buffer 减少内存分配
|
||||
binary.LittleEndian.PutUint64(ri.entryBuf[:], uint64(offset))
|
||||
|
||||
if _, err := ri.indexFile.Write(entryBuf); err != nil {
|
||||
if _, err := ri.indexFile.Write(ri.entryBuf[:]); err != nil {
|
||||
return fmt.Errorf("append index entry: %w", err)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user