Reputation: 21
As far as I know, JavaScript code goes through two phases: compilation phase and execution phase, when a JavaScript engine like V8 runs our code. I wonder when the heap memory is actually allocated for a function. More specifically, if I declare function and not call it in our code, does the JavaScript engine such as V8 still allocate memory for the function in the compilation phase?
Thank you
Upvotes: 2
Views: 1208
Reputation: 40501
It's a bit more complicated than just two phases. Engines typically try to save memory when they can, but nothing is entirely free. It's safe to assume that a function that's never called consumes less memory than one that is called, but not zero.
In V8 in particular, (most) code is at first "pre-parsed". The preparser leaves behind some metadata about functions it has seen; mostly where in the source they start/end and some information about which variables from their outer context, if any, they'll need.
When program execution reaches a point where a function becomes available to JavaScript (as a variable), an actual object is created for it. This function object does not contain code or bytecode yet.
When a function is called, it is just-in-time compiled to bytecode. From this point on, memory is consumed for the bytecode.
If V8 notices that a lot of time is spent in the function, it may decide to generate optimized code for it. Optimized code is stored in addition to the bytecode, so the function's memory consumption grows again. Some functions never reach this point (e.g. when they're only called a few times).
Of course, when a function is executed, it can create other objects. (That's probably not what you're asking; just mentioning it for completeness.)
Upvotes: 1