我實現以下鏈接列表數據結構在JavaScript:JavaScript的鏈表曹景偉垃圾收集
class Node {
constructor(data, list) {
this.data = data;
this.list = list;
this.prev = null;
this.next = null;
}
remove() {
if (this.prev) {
this.prev.next = this.next;
} else {
this.list.start = this.next;
}
if (this.next) {
this.next.prev = this.prev;
} else {
this.list.end = this.prev;
}
this.next = null;
this.prev = null;
this.list.length -= 1;
}
}
class LinkedList {
constructor() {
this.end = null;
this.start = null;
this.length = 0;
}
append(data) {
const node = new Node(data, this);
if (!this.start) {
this.start = node;
}
if (this.end) {
node.prev = this.end;
this.end.next = node;
}
this.end = node;
this.length += 1;
return data;
}
remove() {
if (this.end) {
return this.end.remove();
}
}
*[Symbol.iterator]() {
let current = this.start;
while (current) {
yield current;
current = current.next;
}
}
}
module.exports = LinkedList;
我用它像這樣更新的動畫列表:
static update(timeDelta) {
for (let node of this.animations) {
const animation = node.data;
if (animation.animating) {
animation.update(timeDelta);
} else {
node.remove();
}
}
}
的node.remove()
線在我的比賽中造成非常明顯的滯後。我懷疑這是觸發垃圾收集。相反,如果我註釋掉node.remove()
這一行並允許鏈表永久增長,那麼遊戲運行平穩。
不斷添加和刪除動畫。我加了一些記錄在動畫update
功能:
start iterating linked list
removing
ms elapsed: 0.45499999999992724
end iterating
start iterating linked list
removing
ms elapsed: 0.455000000000382
end iterating
start iterating linked list
removing
ms elapsed: 0.13000000000010914
end iterating
start iterating linked list
(13) updating
ms elapsed: 2.200000000000273
end iterating
你可以看到鏈表是每秒迭代多次與被刪除偶爾節點。
如何在不引起性能下降的情況下從我的列表中實現O(1)刪除?
使用鏈表的目的是什麼?你不能只使用數組或對象嗎? –
我可以使用一個數組,但我試圖避免使用'splice',這將不得不將所有元素轉移。我想要定時去除元素。 –
然後你可以使用一個對象。 –