简体   繁体   English

Javascript模块声明 - 性能

[英]Javascript Module declaration - performance

I am trying to decide between the following ways of writing JS module. 我试图在以下方式之间决定编写JS模块。 What are the implications of writing a module on Memory and CPU. 在内存和CPU上编写模块有什么含义。 Will the 2nd one take up more Memory in the browser ? 第二个会在浏览器中占用更多内存吗?

Using function declaration 使用函数声明

function MyModule () {
    this.getOperation1 =  operation1;
    function operation1() {
        return "XYZ"
    }
}

Using variable definition 使用变量定义

 var MyModule = {
     getOperation1: function() {
        return "XYZ"
     }
  }

Memory wise they're about the same - both create a single object. 记忆明智他们大致相同 - 都创造了一个单一的对象。

However: 然而:

  1. You can only use new with the function based module format. 您只能使用基于功能的模块格式的new The latter just creates a single object, not a constructor that can be used to create additional instances. 后者只创建一个对象,而不是可用于创建其他实例的构造函数。

  2. With a function you can enclose private local variables in the scope. 使用函数,您可以在范围中包含私有局部变量。

However, in most cases a better approach is this: 但是,在大多数情况下,更好的方法是:

function MyModule () {
}

MyModule.prototype.getOperation1 = function() {
    ...
}

which ensures that if you create multiple instances they all only share one copy of the getOperation1 function. 这确保了如果您创建多个实例,它们只共享getOperation1函数的一个副本。

That said, if all you're trying to do is namespace the functions, and they don't naturally form an "object' (in the OOP sense) then you might just as well use the object literal syntax. 也就是说,如果您要做的就是命名函数,并且它们不会自然形成“对象”(在OOP意义上),那么您也可以使用对象文字语法。

Refer this yui-blog for memory related argument 请参阅yui-blog以获取与内存相关的参数

From the same 来自同一个

By using new to invoke the function, the object holds onto a worthless prototype object. 通过使用new来调用函数,该对象保持一个毫无价值的原型对象。 That wastes memory with no offsetting advantage. 这浪费了记忆,没有抵消优势。 If we do not use the new, we don't keep the wasted prototype object in the chain 如果我们不使用new,我们不会将浪费的原型对象保留在链中

As mentioned by @Alnitak make use of prototype object incase you are up to implement constructor function so that all instances would share the same object. 正如@Alnitak所提到的,使用prototype对象,你需要实现constructor函数,以便所有实例共享同一个对象。

To check CPU wise [speed] use www.jsperf.com and do a performance test. 要检查CPU智能[速度],请使用www.jsperf.com并进行性能测试。 Some already available tests Function Invocation , Object.create vs new , Generic 一些已经可用的测试函数调用Object.create与newGeneric

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM