[英]How much memory does a JavaScript declared function consume on script loading?
I have taken some JavaScript courses lately (at codeschool ) and, in one of them, they said: 我最近(在codeschool )上过一些JavaScript课程,其中之一是,他们说:
Thus fe has an advantage over fd which is saving some memory at loading time - I concluded. 因此,相对于fd,fe具有优势,后者在加载时节省了一些内存 -我得出结论。
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. 因此,例如,考虑下面的两个片段代码,加载时将不会有任何额外的内存分配,因为由于提升,会将foo
分配给undefined
。
// 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. 简而言之, foo
是undefined
并且仅在代码运行后才将函数表达式分配给foo
。 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. 但是,“ 如果fe比fd有优势,那就是在加载时节省了一些内存 ”,下面的代码应该在加载时分配一些额外的内存,因为它是函数声明。
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? 如果是这样,加载时需要占用多少内存,以及如何计算?
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. 您可以通过在创建函数之前和之后执行堆转储来执行一些测试,但是实际数量会随着添加和删除优化而有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.