github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/router/pool.go (about) 1 package router 2 3 import ( 4 "reflect" 5 "sync" 6 ) 7 8 /* 9 TODO 等待重构 10 */ 11 12 type ( 13 pool struct { 14 active bool 15 pools map[reflect.Type]*sync.Pool 16 New func(t reflect.Type) reflect.Value 17 } 18 ) 19 20 // TODO 使用字符串名称 21 // TODO 测试效率 22 func newPool() *pool { 23 return &pool{ 24 active: true, 25 pools: make(map[reflect.Type]*sync.Pool), //@@@ 改进改为接口 String 26 New: func(t reflect.Type) reflect.Value { 27 var argv reflect.Value 28 29 if t.Kind() == reflect.Ptr { 30 argv = reflect.New(t.Elem()) 31 } else { 32 argv = reflect.New(t) 33 } 34 35 return argv 36 }, 37 } 38 } 39 40 func (self *pool) Active(open bool) { 41 self.active = open 42 } 43 44 //@@@ 改进改为接口 45 // Resul:nil 当取不到时直接返回Nil 方便外部判断 46 // TODO:优化速度 47 func (self *pool) Get(object reflect.Type) reflect.Value { 48 if object == nil { 49 return reflect.ValueOf(nil) 50 } 51 52 if !self.active { 53 return self.New(object) 54 } 55 56 if pool, ok := self.pools[object]; ok { 57 itf := pool.Get() 58 if itf == nil { 59 //return reflect.New(object).Elem() 60 return self.New(object) 61 } 62 63 return itf.(reflect.Value) 64 } else { 65 //return reflect.New(object).Elem() 66 return self.New(object) 67 } 68 } 69 70 func (self *pool) Put(typ reflect.Type, val reflect.Value) { 71 if !self.active { 72 return 73 } 74 75 if pool, ok := self.pools[typ]; ok { 76 pool.Put(val) 77 } else { 78 pool := new(sync.Pool) 79 80 pool.Put(val) 81 self.pools[typ] = pool 82 } 83 }