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
}
2
Answers
Brief Answer: No
The code will not allocate memory for the variables and objects in the early-return case.
You can verify this in several ways. One of the simplest methods is to assign a large object to
smth
.Example Code (Run this in the browser console):
Observation:
Node.js Compatibility:
This behavior also works in Node.js (tested on my computer with Node.js 20.12.2):
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.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.