Reputation: 1282
I have taken some JavaScript courses lately (at codeschool) and, in one of them, they said:
Thus fe has an advantage over fd which is saving some memory at loading time - I concluded.
So, for example, considering following two snipped codes below, there won't be any extra memory allocation on loading time because foo
is going to be assigned to undefined
thanks to hoisting.
// Original code
var foo = function (bar) {
console.log(bar);
};
Below we have code after hoisting
// Code after hoisting
var foo = undefined;
foo = function (bar) {
console.log(bar);
};
In shortness, foo
is undefined
and the function expression will only be assigned to foo
once code runs. Thus it won't allocate extra memory on loading time.
Ok. No problems till now. However, "if fe has an advantage over fd which is saving some memory at loading time" following code should take some extra memory to be allocated at loading time since it's a function declaration.
function foo(bar) {
console.log(bar);
}
So the question is: is my reasoning right? If so, how much memory does it take at loading time and how is it calculated?
Upvotes: 0
Views: 156
Reputation: 32511
Yes, you're right because all function declarations are hoisted to the top and (usually) compiled on the spot. Function expressions aren't generally compiled until run-time because they may or may not be used at all:
var f;
if (condition) {
f = function() { ... };
}
// f could be undefined
As for how much memory it takes, that depends on the engine implementation. How they store:
all depends on the internal design of the engine. You could perform some testing by performing a heap dump before and after functions are created but that actual number would vary as optimizations are added and dropped.
Upvotes: 3