-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
73 lines (65 loc) · 1.45 KB
/
pool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package qjson
import (
"sync"
"sync/atomic"
"unsafe"
)
var (
nodePool = &sync.Pool{New: func() interface{} { return new(Node) }}
objectPool = &sync.Pool{New: func() interface{} { return new(ObjectElem) }}
strsPool = &sync.Pool{New: func() interface{} { return new(strSlice) }}
)
// Release json tree for objects reuse
func (tree *JSONTree) Release() {
if node := tree.Root; node != nil {
if atomic.CompareAndSwapPointer((*unsafe.Pointer)((unsafe.Pointer)(&tree.Root)), unsafe.Pointer(node), unsafe.Pointer(nil)) {
nodePool.Put(node)
}
}
}
// CreateNode by pool
func CreateNode() *Node {
node := nodePool.Get().(*Node)
if node.ObjectValues != nil {
for i := range node.ObjectValues {
objectPool.Put(node.ObjectValues[i])
}
node.ObjectValues = nil
}
if node.ArrayValues != nil {
for i := range node.ArrayValues {
nodePool.Put(node.ArrayValues[i])
}
node.ArrayValues = nil
}
node.Value = emptyVal
node.Type = Null
node.hashId = 0
return node
}
// CreateObjectElem by pool
func CreateObjectElem() *ObjectElem {
object := objectPool.Get().(*ObjectElem)
if object.Key != nil {
nodePool.Put(object.Key)
object.Key = nil
}
if object.Value != nil {
nodePool.Put(object.Value)
object.Value = nil
}
return object
}
type strSlice struct {
Str []string
}
func getStrSlice() *strSlice {
ss := strsPool.Get().(*strSlice)
if ss.Str != nil {
ss.Str = ss.Str[:0]
}
return ss
}
func putStrSlice(ss *strSlice) {
strsPool.Put(ss)
}