E_Jovi E_Jovi - 3 months ago 11
Javascript Question

compare memory usage between variables outside es6 class and bind to this

I wonder which way is better in real run-time about memory footprint and release time.

outside class



const foo = {
...
};

class Base {
// use foo below as const variables
}


bind to this as property



class Base {
constructor() {
this.bar = {
...
}
}

// use this.bar as property below
}


which way above will occupy more memory?
if I follow the first one that define const variables outside class, what time which be released from memory?

thanks for your time :)

Answer

In the first case a single foo object will be hold in memory until the realm is shut down.

In the second case it will be an instance of this.bar per Base.

Keeping in mind the Garbage Collector:

  1. Is not standardised and not even required for an implementation
  2. Is not deterministic (can run at any point in time, or never)

Based on that we can speculatively state that:

First case is "better"* if at least one instance of Base is created.

And now addressing your very questions:

if I follow the first one that define const variables outside class, what time which be released from memory?

An object would become garbage collectible when it's not reachable. So, when all references to it are lost. Then, the memory is "released" after the GC is triggered.

But practically, you must follow the performance optimisation rule of thumb: measure.

If something is a problem for you, first take debugger/profiler and prove scientifically it actually is what you think it is.


*It all really depends