github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/luacontpool.go (about) 1 //go:build !nocontpool 2 // +build !nocontpool 3 4 package runtime 5 6 // Size of the LuaCont pool. Setting it to 0 makes luaContPool.get() behave 7 // like new(LuaCont) and luaContPool.release(c) be a no-op. The value of 100 was 8 // reached by trial-and-error but is probably not optimal. 9 const luaContPoolSize = 100 10 11 // Pool for reusing allocated Lua continuations. Some profiling 12 // showed there was significant overhead to allocating lua continuations all the 13 // time on the heap. This is a very simple implementation, but it reduces 14 // significantly pressure on memory management for a fair range of workloads. 15 type luaContPool struct { 16 conts [luaContPoolSize]*LuaCont 17 next int 18 } 19 20 // Get a LuaCont from the pool (or make a new one if the pool is empty). Note 21 // that it is ok not to release this LuaCont to the pool later - if it is not 22 // released but becomes unreachable, then it will be GCed at some point by the 23 // Go runtime 24 func (p *luaContPool) get() *LuaCont { 25 if p.next == 0 { 26 return new(LuaCont) 27 } 28 p.next-- 29 c := p.conts[p.next] 30 p.conts[p.next] = nil 31 return c 32 } 33 34 // Return a used LuaCont into the pool (this will first erase the fields of the 35 // continuation, to allow GC of the data they contain). If the pool is full, 36 // the continuation is simply discarded. 37 func (p *luaContPool) release(cont *LuaCont) { 38 *cont = LuaCont{} 39 if p.next == luaContPoolSize { 40 return 41 } 42 p.conts[p.next] = cont 43 p.next++ 44 }