Mutability Of Typescript Interface Instances (objects)

- 1 answer

I've found interfaces to be super useful, but as I need to start optimizing my app due to memory problems I've realized that I don't really understand how they work internally.

Say I have

interface Foo {
  bar: number

And I instantiate some variable with this typing:

let x : Foo = { bar: 2 }

Q1: Does this create a new object?

Now, let's say I want to change the value of bar. I do it one of two ways. First way:

x = { bar: 5 }

Q2: Does this first way create a new object and replace the old object referenced by x, causing the old object (with bar = 2) to eventually be garbage collected?

Second way: = 5

Q3: Does this not create a new object, and instead just updates the value of bar in the first object (which had bar = 2) and avoids garbage collection since there is still only one object and it's in use?

I believe the answers to my questions are Yes, Yes, and Yes. But I want to be sure since I'm having a real headache dealing with overly-frequent garbage collection and I think the fact that many parts of my code use the "first way" instead of the second may be a big contributing factor.



Your answers (Yes, Yes, and Yes) are correct. And if you're replacing objects with new ones (x = {bar: 5}) a lot, then yes, that will mean that the garbage collector has more work to do compared with doing = 5 instead.

Re Q2: x = {bar: 5} creates a new object and means the old object referenced by x is available for garbage collection if nothing else still has a reference to the old object that x referred to. Otherwise, if something still has a reference to what x used to refer to, e.g.:

let y = x;
x = {bar: 5};

...then the object x used to refer to will stick around (since y refers to it) until/unless y no longer refers to it (because you assign a different value to y or because y goes out of scope and isn't referenced by a closure).