package astar6 import "sync" // contextPool 搜索上下文对象池 // 通过复用SearchContext减少GC压力,提升并发性能 var contextPool = sync.Pool{ New: func() interface{} { return &FindContext{ openSet: make(map[*Node]*heapItem, 512), // 优化:增加初始容量 closeSet: make(map[*Node]struct{}, 512), parentMap: make(map[*Node]*Node, 512), gMap: make(map[*Node]int32, 512), } }, } // heapItemPool heapItem对象池 // 优化:复用heapItem对象,减少GC压力 var heapItemPool = sync.Pool{ New: func() interface{} { return &heapItem{} }, } // acquireContext 从对象池获取搜索上下文 func acquireContext() *FindContext { ctx := contextPool.Get().(*FindContext) return ctx } // releaseContext 释放搜索上下文回对象池 // 清理所有状态以便下次复用 // 优化:使用clear()替代循环删除(Go 1.21+) func releaseContext(ctx *FindContext) { ctx.openHeap = ctx.openHeap[:0] // 重置切片长度但保留底层数组 // 优化:使用clear()清空map,同时将heapItem归还对象池 for _, item := range ctx.openSet { heapItemPool.Put(item) } clear(ctx.openSet) clear(ctx.closeSet) clear(ctx.parentMap) clear(ctx.gMap) ctx.start = nil ctx.end = nil contextPool.Put(ctx) } func getHeapItem() *heapItem { return heapItemPool.Get().(*heapItem) }