From TypeScript point of View
I want to know is there any way to destroy static variables,static array in TypeScript
I know we can make it null but want to destroy in order to save memory.
This question may be dumb little but need help because in my project i have a lot use of static variables and static array.
-
Your Application's memory management has nothing to do with TypeScript. TypeScript is a design time language and your code will actually transpile to JavaScript. So whatever you're writing will eventually be JavaScript. That being said, JavaScript being a high-level language has it's own Garbage Collector that frees up memory when not used. It uses algorithms like Mark and Sweep to collect up unused memory. So there's nothing that you have to do while developing in JavaScript apart from avoiding any memory leaks.SiddAjmera– SiddAjmera2018-09-26 08:30:39 +00:00Commented Sep 26, 2018 at 8:30
-
does this garbage collector will collect static variables too? if yes then can you provide examplechokiChoki– chokiChoki2018-09-26 08:37:32 +00:00Commented Sep 26, 2018 at 8:37
-
If you go to typescriptlang.org/play, and type a class with a static and a non-static property on it, you'll notice that static members are nothing but properties on the Class and not on class's instance. So I think when the class is not used anywhere, it would be garbage collected and the static properties would be garbage collected with it.SiddAjmera– SiddAjmera2018-09-26 08:53:54 +00:00Commented Sep 26, 2018 at 8:53
3 Answers
I will quote this "
o4 = null;`
// 'o4' has zero references to it.
// It can be garbage collected."
What this means by make it "null" you make the object array or whatever ready for the GC and the GC will clear it out of your memory.
So by making it null you will clear it out of the memory.
6 Comments
Usually when you removes references to the object (assuming nobody else is using it). The garbage collector will free up the memory.
There are basically 2 solutions to this problem, Use function scope or else dereference them manually.
6 Comments
Destroy or Set to null?
If you are using the delete keyword, it will remove the property itself.
let obj = {a:1, b:2}
delete obj.a
console.log(obj)
// {b:2}
If you are assigning a null to a property, it will remove reference to the object.
Note: However, it will not free up memory if other references to that object exists.
let obj = {a:1, b:2}
obj.a = null
console.log(obj)
// {a:null, b:2}
To my knowledge, there is no guarantee to trigger the Garbage Collector in browsers. Here's a reference.