Skip to content

Instantly share code, notes, and snippets.

@ahmedosama-st
Last active December 16, 2024 10:38
Show Gist options
  • Save ahmedosama-st/8ce76cc060e1e54b9063224f5ab5524a to your computer and use it in GitHub Desktop.
Save ahmedosama-st/8ce76cc060e1e54b9063224f5ab5524a to your computer and use it in GitHub Desktop.
Garbage collector Mark And Sweep example in TS
class GarbageCollector {
public heap: Set<object>;
constructor() {
this.heap = new Set(); // Simulates the heap where all objects are stored
}
allocate(obj) {
this.heap.add(obj); // Add the object to the heap
return obj;
}
mark(root) {
const visited = new Set();
const traverse = (node) => {
if (node && !visited.has(node)) {
visited.add(node); // Mark the node as visited
for (const key in node) {
if (typeof node[key] === 'object') {
traverse(node[key]); // Recursively traverse child objects
}
}
}
};
traverse(root); // Start marking from the root object
return visited;
}
sweep(marked) {
for (const obj of this.heap) {
if (!marked.has(obj)) {
this.heap.delete(obj); // Remove unmarked objects from the heap
console.log(
`Object with value ${JSON.stringify(obj)} has been garbage collected.`
);
}
}
}
collectGarbage(root) {
console.log('Starting garbage collection...');
const marked = this.mark(root); // Mark phase
this.sweep(marked); // Sweep phase
console.log('Garbage collection completed.');
}
}
// Initialize garbage collector
const gc = new GarbageCollector();
// Step 1: Initialize object A
let A = gc.allocate({ value: 1 });
// Step 2: Add objects B, C, and D
let B = gc.allocate({ value: 2 });
A.B = B; // A points to B
A.C = gc.allocate({ value: 3 }); // A points to C
B.D = gc.allocate({ value: 4 }); // B points to D
// Step 3: Add object E to C
A.C.E = gc.allocate({ value: 5 }); // C points to E
// Simulate the heap and object structure
console.log('Heap after initialization:', Array.from(gc.heap));
// Step 4: Remove reference to B
delete A.B; // D becomes unreachable
// Perform garbage collection
gc.collectGarbage(A);
// Simulate the heap after garbage collection
console.log('Heap after garbage collection:', Array.from(gc.heap));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment