javascript - Javascript中隐藏信息会牺牲性能吗?

标签 javascript node.js

我的主要问题如下:

is information hidding going to hurt perfomance(Both CPU/Memory) when you have a frequently-accessed function (returning an object) that you want people to interact with?

或者这是否被认为是微优化,特别是在使用像node.js(长时间运行的进程)这样的平台时。我是否应该考虑性能而不是信息隐藏?

<小时/>

通过阅读Douglas Crockford's article about information hidding我知道我可以添加私有(private)成员和特权方法。但根据 Douglas Crockford 的这句话,原型(prototype)机制可以帮助您节省内存:

When a member is sought and it isn't found in the object itself, then it is taken from the object's constructor's prototype member. The prototype mechanism is used for inheritance. It also conserves memory.

当只保存内存时,我想这可能不是什么大问题,因为内存正在变得越来越便宜。但根据this article from John Resig在原型(prototype)链中添加很多属性也更快(CPU)。

Thus, if you have a frequently-accessed function (returning an object) that you want people to interact with, then it's to your advantage to have the object properties be in the prototype chain and instantiate it.

Instantiating a function with a bunch of prototype properties is very, very, fast. It completely blows the Module pattern, and similar, out of the water. Thus, if you have a frequently-accessed function (returning an object) that you want people to interact with, then it's to your advantage to have the object properties be in the prototype chain and instantiate it.

// Very fast
function User(){}
User.prototype = { /* Lots of properties ... */ };
// Very slow
function User(){
  return { /* Lots of properties */ };
}

这也可能不是一个大问题,因为 CPU 的速度越来越快(摩尔定律)。此外,由于 Javascript 引擎在性能方面取得了令人难以置信的进步,我想知道我是否应该考虑这一点,或者只是使用信息隐藏。

<小时/>

我猜我还有这个子问题:

How would I effectively measure both memory and CPU using a platform like for example node.js?

最佳答案

这对我来说听起来确实像是您试图过度优化很少需要优化的东西。首先写下你的成本是可靠的,其次是你或其他人可以维护的,然后在你得到需要优化的证据后,只优化真正需要优化的东西。

首先,让事情变得真正私密会增加复杂性。除非您真的非常需要隐私,否则您可能应该使用成员变量。

其次,实现隐私的闭包确实会带来某种内存消耗成本。每次使用的内存量很小,因此如果您确实需要隐私(第一点),那么除非您有很多这样的闭包,否则您可能甚至不会注意到额外的消耗。

第三,如果您有很多这些对象(例如数千个)并且您怀疑内存消耗实际上可能是一个重要问题,那么您可能应该在几个流行的浏览器中进行快速内存测试(其中一个版本具有私有(private)闭包和具有更简单的公共(public)成员变量的闭包),看看有多少差异。差异是特定于实现的,因此不同浏览器之间可能存在很大差异。

根据这些测量结果,您可以决定走哪条路。

如果您没有数千个这样的对象,那么请以尽可能简单的方式编写代码来实现您的目标,并将时间花在一些事情上,以表明它们在您运行应用程序后确实很重要。

关于javascript - Javascript中隐藏信息会牺牲性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11497798/

相关文章:

javascript - 使用 JavaScript 修改 "Span"时禁用悬停效果

javascript - JSONP 仅适用于命名回调函数

node.js - Firestore 函数 listCollections() 仅返回空数组

javascript - 控制台以连续模式记录函数并打印函数实现

javascript - 如何使用顶级数组中的 amp-selector 设置对象以在 amp-bind 中使用

javascript - document.click 以删除页面上的类行为不正常

node.js - 当我需要验证数组的内容时,NestJS 中的 ValidationPipe 出现问题

node.js - 从正在运行的 node.js 应用程序确定项目根

javascript - Angular 应用程序没有渲染任何内容

node.js - 使用wkhtmltopdf时出错