詳細介紹 JavaScript 中的引用計數垃圾回收?


 引用計數垃圾回收

這是最簡單的垃圾回收演算法。此演算法尋找那些沒有任何引用剩下的物件。如果一個物件沒有引用,則它有資格進行垃圾回收。垃圾回收在下面的示例中進行了說明。

示例

var obj = {
      x: { y: 2 }
         };
         // 2 objects created. One is referenced by the other as one of its properties.
         // Obviously, none can be garbage-collected
obj = 1; // what was the 'x' property of the object originally in obj
         // has zero references to it. It can be garbage collected.

限制

在**迴圈**方面,引用計數垃圾回收存在限制,並在下面的示例中進行了解釋。

示例

在以下示例中,建立了兩個物件並相互引用,從而建立了一個迴圈。函式呼叫後,它們將超出範圍,因此它們實際上是無用的,可以被釋放。但是,引用計數演算法認為,由於這兩個物件中至少有一個被引用了一次,因此沒有一個是垃圾回收的。

function f() {
var obj1 = {};
var obj2 = {};
obj1.p = obj2; // o1 references o2
obj2.p = obj1; // o2 references o1. This creates a cycle.
}
f();

更新於: 30-7-2019

3K + 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.