Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Typescript / Javascript garbage collector handle circular references or does it leak memory? [duplicate]

In languages like C# this isn't a problem, but this creates hard to find memory bugs in some other languages. Can I use the following code in Typescript or Javascript and trust that everything will be fine?

class Dad {
    kids: Kid[];
}
class Kid {
    dad: Dad;
    siblings: Kid[];
}

let anakin: Dad | undefined;

function makeKids(dad: Dad) {
    const luke = new Kid();
    const leia = new Kid();
    luke.dad = dad;
    leia.dad = dad;
    luke.siblings = [leia];
    leia.siblings = [luke];
    dad.kids = [luke, leia];
}

anakin = new Dad();
makeKids(anakin);
console.log(anakin.kids.length); // Prints out 2
anakin = undefined;
// I expect luke and leia to die at this point
// Not float around the memory space infinitely

Or should I make the variable kids and siblings optional and add a destructor? Something like this:

kids?: Kid[];
siblings?: Kid[];
destructor() {
    this.kids = undefined
}

Here is a related topic and I wasn't satisfied with the answer: Destroy an circular-reference instance in typescript?

like image 818
Esqarrouth Avatar asked Jan 19 '26 22:01

Esqarrouth


1 Answers

TypeScript doesn't have a runtime.

There are many JavaScript runtimes, so it's impossible to say some particular thing is true of all of them, but all the major runtimes (those shipped in popular browsers, node.js) are easily capable of dealing with disconnected circular references.

There is a well-defined memory root in JS from which it's easy to do a mark-and-sweep GC, which has no problems dealing with circular references. Circular references are really only an issue in ref-counted GC systems and there's no great reason to do ref counting in the JS language since you don't need deterministic cleanup.

like image 61
Ryan Cavanaugh Avatar answered Jan 22 '26 10:01

Ryan Cavanaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!