Skip to content

Commit 7804f5b

Browse files
committed
Use sync.Pool for LinkedListQueue to recycle nodes as possible
1 parent 01f5707 commit 7804f5b

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

queue.go

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -281,13 +281,30 @@ type LinkedListQueue struct {
281281
last *DoublyListItem
282282
count int
283283

284+
nodeGCPool sync.Pool
284285
nodePoolFirst *DoublyListItem
285286
nodeCount int
286287
}
287288

288289
// NewLinkedListQueue New LinkedListQueue instance
289290
func NewLinkedListQueue() *LinkedListQueue {
290-
return new(LinkedListQueue)
291+
newOne := new(LinkedListQueue)
292+
newOne.nodeGCPool.New = func() interface{} {
293+
return new(DoublyListItem)
294+
}
295+
return newOne
296+
}
297+
298+
func (q *LinkedListQueue) putAllIntoPool(first *DoublyListItem) {
299+
for first != nil {
300+
node := first
301+
first = first.Next
302+
303+
node.Val = nil
304+
node.Prev = nil
305+
node.Next = nil
306+
q.nodeGCPool.Put(node)
307+
}
291308
}
292309

293310
// Count Count Items
@@ -297,6 +314,8 @@ func (q *LinkedListQueue) Count() int {
297314

298315
// ClearNodePool Clear cached LinkedListItem nodes in nodePool
299316
func (q *LinkedListQueue) ClearNodePool() {
317+
q.putAllIntoPool(q.nodePoolFirst)
318+
300319
q.nodeCount = 0
301320
q.nodePoolFirst = nil
302321
}
@@ -313,17 +332,18 @@ func (q *LinkedListQueue) KeepNodePoolCount(n int) {
313332
n--
314333
last := q.nodePoolFirst
315334
if last == nil {
316-
last = new(DoublyListItem)
335+
last = q.nodeGCPool.Get().(*DoublyListItem)
317336
q.nodePoolFirst = last
318337
}
319338

320339
for n > 0 {
321340
n--
322341
if last.Next == nil {
323-
last.Next = new(DoublyListItem)
342+
last.Next = q.nodeGCPool.Get().(*DoublyListItem)
324343
}
325344
last = last.Next
326345
}
346+
q.putAllIntoPool(last.Next)
327347
last.Next = nil
328348
}
329349

@@ -455,7 +475,7 @@ func (q *LinkedListQueue) Push(val interface{}) error {
455475
func (q *LinkedListQueue) generateNode() *DoublyListItem {
456476
node := q.nodePoolFirst
457477
if node == nil {
458-
node = new(DoublyListItem)
478+
node = q.nodeGCPool.Get().(*DoublyListItem)
459479
} else {
460480
q.nodeCount--
461481
q.nodePoolFirst = node.Next

0 commit comments

Comments
 (0)