创建函数是否会消耗更多内存 [英] Does creating functions consume more memory

查看:122
本文介绍了创建函数是否会消耗更多内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Case A
function Constructor() {
  this.foo = function() {
    ...
  };
  ...
}

// vs 
// Case B
function Constructor() {
  ...
};

Constructor.prototype.foo = function() {
  ...
}

人们建议使用原型的主要原因之一是 .foo 在原型的情况下创建一次,其中 .foo 当使用其他方法时,c $ c> this.foo 被多次创建。

One of the main reasons people advise the use of prototypes is that .foo is created once in the case of the prototype where as this.foo is created multiple times when using the other approach.

然而,人们会期望解释器可以优化它。因此在A情况下只有一个函数 foo 的副本。

However one would expect interpreters can optimize this. So that there is only one copy of the function foo in case A.

当然你仍然会有一个每个对象的唯一范围上下文,因为闭包,但开销少于每个对象的新函数。

Of course you would still have a unique scope context for each object because of closures but that has less overhead then a new function for each object.

现代JS解释器是否优化案例A,因此只有一个副本函数 foo

Do modern JS interpreters optimise Case A so there is only one copy of the function foo ?

推荐答案

是的,创建函数会占用更多内存。

Yes, creating functions uses more memory.

...而且,不,解释员不会将案例A优化为单一函数。

... and, no, interpreters don't optimize Case A down to a single function.

原因是 JS范围链要求函数的每个实例捕获可用的变量。它创造的时间。也就是说,现代口译员更好,但很大程度上是因为关闭函数的性能在几年前已成为一个已知问题。

The reason is the JS scope chain requires each instance of a function to capture the variables available to it at the time it's created. That said, modern interpreters are better about Case A than they used to be, but largely because the performance of closure functions was a known issue a couple years ago.

Mozilla说要避免不必要的关闭出于这个原因,但是闭包是JS开发人员工具包中最强大和最常用的工具之一。

Mozilla says to avoid unnecessary closures for this reason, but closures are one of the most powerful and often used tools in a JS developer's toolkit.

更新:只需运行此测试,即使用node.js(即V8,JS)创建构造函数的1M'实例' Chrome中的翻译)。使用 caseA = true 我得到了这个内存使用情况:

Update: Just ran this test that creates 1M 'instances' of Constructor, using node.js (which is V8, the JS interpreter in Chrome). With caseA = true I get this memory usage:

{ rss: 212291584,
vsize: 3279040512,
heapTotal: 203424416,
heapUsed: 180715856 }

并且 caseA = false 我得到了这个内存使用情况:

And with caseA = false I get this memory usage:

{ rss: 73535488,
vsize: 3149352960,
heapTotal: 74908960,
heapUsed: 56308008 }

所以闭包函数肯定会消耗更多的内存,差不多是3倍。但从绝对意义上讲,我们只讨论每个实例约140-150字节的差异。 (但是,根据创建函数时的范围内变量的数量,这可能会增加。)

So the closure functions are definitely consuming significantly more memory, by almost 3X. But in the absolute sense, we're only talking about a difference of ~140-150 bytes per instance. (However that will likely increase depending on the number of in-scope variables you have when the function is created).

这篇关于创建函数是否会消耗更多内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆