For efficient memory usage of a highly used class instance (multiple calls to init
), I would like to know if memory for anything inside init
function is allocated if it returns early.
class X {
private static smth: Smth
public static init(): Smth {
// if this is evalueated to true and returned
if (this.smth) {
return this.smth;
}
// does memory allocated here (imagine there will be a big object)?
const smth: Smth = {
x: 1
}
this.smth = smth
return this.smth
}
// if for previous question answer is yes, can we avoid memory allocation for `const smth` like this?
public static getInstance(): Smth {
if (!this.smth) {
throw new Error("Not initialized");
}
return this.init();
}
}
type Smth = {
x: number
}
The memory for the variable const smth
(which is hoisted) is typically allocated when the function is called, as part of the stack space for that function call. (An engine might be able to optimise this away, but it's hardly worth it - the stack allocation and later deallocation is cheap).
The memory for the "large" object isn't allocated until the object is actually created, i.e. when the expression with the { … }
object literal is evaluated.
If for previous question answer is yes, can we avoid memory allocation for
const smth
like this?
You might be able, yes, but at the cost of an extra function call. The overhead of the stack allocation(s) for a function call is much larger than a single (pointer) variable, so this is unlikely to gain anything.