Skip to content

Commit 07dcfd3

Browse files
committed
Use sync.Pool for LinkedListQueue to recycle nodes as possible
1 parent b1bddc0 commit 07dcfd3

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[T any] struct {
281281
last *DoublyListItem[T]
282282
count int
283283

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

288289
// NewLinkedListQueue New LinkedListQueue instance
289290
func NewLinkedListQueue[T any]() *LinkedListQueue[T] {
290-
return new(LinkedListQueue[T])
291+
newOne := new(LinkedListQueue[T])
292+
newOne.nodeGCPool.New = func() interface{} {
293+
return new(DoublyListItem[T])
294+
}
295+
return newOne
296+
}
297+
298+
func (q *LinkedListQueue[T]) putAllIntoPool(first *DoublyListItem[T]) {
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[T]) Count() int {
297314

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

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

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

0 commit comments

Comments
 (0)