pool.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package astar6
  2. import "sync"
  3. // contextPool 搜索上下文对象池
  4. // 通过复用SearchContext减少GC压力,提升并发性能
  5. var contextPool = sync.Pool{
  6. New: func() interface{} {
  7. return &FindContext{
  8. openSet: make(map[*Node]*heapItem, 512), // 优化:增加初始容量
  9. closeSet: make(map[*Node]struct{}, 512),
  10. parentMap: make(map[*Node]*Node, 512),
  11. gMap: make(map[*Node]int32, 512),
  12. }
  13. },
  14. }
  15. // heapItemPool heapItem对象池
  16. // 优化:复用heapItem对象,减少GC压力
  17. var heapItemPool = sync.Pool{
  18. New: func() interface{} {
  19. return &heapItem{}
  20. },
  21. }
  22. // acquireContext 从对象池获取搜索上下文
  23. func acquireContext() *FindContext {
  24. ctx := contextPool.Get().(*FindContext)
  25. return ctx
  26. }
  27. // releaseContext 释放搜索上下文回对象池
  28. // 清理所有状态以便下次复用
  29. // 优化:使用clear()替代循环删除(Go 1.21+)
  30. func releaseContext(ctx *FindContext) {
  31. ctx.openHeap = ctx.openHeap[:0] // 重置切片长度但保留底层数组
  32. // 优化:使用clear()清空map,同时将heapItem归还对象池
  33. for _, item := range ctx.openSet {
  34. heapItemPool.Put(item)
  35. }
  36. clear(ctx.openSet)
  37. clear(ctx.closeSet)
  38. clear(ctx.parentMap)
  39. clear(ctx.gMap)
  40. ctx.start = nil
  41. ctx.end = nil
  42. contextPool.Put(ctx)
  43. }
  44. func getHeapItem() *heapItem {
  45. return heapItemPool.Get().(*heapItem)
  46. }