简体   繁体   English

将Javascript代码封装在对象中是否会影响性能?

[英]Does encapsulating Javascript code in objects affect performance?

I am wondering if it is more or less efficient to encapsulate the main body of your JavaScript code in an object? 我想知道将JavaScript代码的主体封装在一个对象中是效率更高还是效率更低? This way the entire scope of your program would be separated from other scopes like window. 这样,您的程序的整个范围将与其他范围(例如window)分开。

For example, if I had the following code in a JavaScript file: 例如,如果我在JavaScript文件中包含以下代码:

/* My main code body. */
var somevar1=undefined;
var somevar2=undefined;
var somevarN=undefined;

function somefunction(){};

function initialize(){/* Initializes the program. */};
/* End main code body. */

I could instead encapsulate the main code body in an object: 我可以将主要代码主体封装在一个对象中:

/* Encapsulating object. */
var application={};
application.somevar1=undefined;
application.somevar2=undefined;
application.somevarN=undefined;

application.somefunction=function(){};

application.initialize=function(){/* Initializes the program. */};

My logic is that since JavaScript searches through all variables in a scope until the right one is found, keeping application specific functions and variables in their own scope would increase efficiency, especially if there were a lot of functions and variables. 我的逻辑是,由于JavaScript会搜索范围内的所有变量直到找到正确的范围,因此将特定于应用程序的功能和变量保持在自己的范围内会提高效率,尤其是在有很多功能和变量的情况下。

My only concern is that this is bad practice or that maybe this would increase the lookup time of variables and functions inside the new "application" scope. 我唯一担心的是这是一种不好的做法,或者可能会增加新的“应用程序”范围内变量和函数的查找时间。 If this is bad practice or completely useless, please let me know! 如果这是不好的做法或完全没用,请告诉我! Thank you! 谢谢!

I've no idea what the performance implications are (I suspect they're negligible either way, but if you're really concerned, test it), but it's very common practice in JavaScript to keep chunks of code in their own scope, rather than having everything in the global scope. 我不知道对性能的影响是什么(我怀疑它们的两种方法都可以忽略不计,但是如果您真的很担心,请对其进行测试),但是在JavaScript中将代码块保留在自己的范围内是非常普遍的做法,而不是将一切都放在全球范围内。

The main benefit is reducing the risk of accidentally overwriting variables in the global scope, and making naming easier (ie you have window.application.initialize instead of eg window.initialize_application ). 主要好处是降低了意外覆盖全局范围内的变量的风险,并使命名更容易(即,您拥有window.application.initialize而不是例如window.initialize_application )。

Instead of your implementation above, you can use self-calling functions to create an area of scope just for one bit of code. 除了上面的实现,您还可以使用自调用函数为一个代码位创建一个作用域区域。 This is known as the module pattern . 这称为模块模式

This has the added advantage of allowing you to create “private” variables that are only accessible within the module, and so aren't accessible from other code running in the same global object: 这具有额外的优点,即允许您创建“私有”变量,这些变量只能在模块内访问,因此无法从在同一全局对象中运行的其他代码访问:

/* Encapsulating object. */
var application=( function () {
    var someprivatevar = null// This can't be accessed by code running outside of this function
      , someprivatefunction = function () { someprivatevar = someprivatevar || new Date(); };

    return {
        somevar1: undefined
      , somevar2: undefined
      , somevarN: undefined
      , somefunction: function(){}
      , getInitialized: function () { return someprivatevar; }
      , initialize: function (){/* Initializes the program. */ someprivatefunction(); }
    };

})();

application.initialize();
application.getInitialized();// Will always tell you when application was initialized

I realize you asked a yes or no question. 我知道您问的是或否的问题。 However, my answer is don't worry about it, and to back that up, I want to post a quote from Eloquent Javascript , by Marijn Haverbeke. 但是,我的答案是不用担心,为此,我想发表一段Marijn Haverbeke的Eloquent Javascript引文。

The dilemma of speed versus elegance is an interesting one. 速度与优雅之间的困境是一个有趣的问题。 You can see it as a kind of continuum between human-friendliness and machine-friendliness. 您可以将其视为人类友好和机器友好之间的一种连续体。 Almost any program can be made faster by making it bigger and more convoluted. 通过使程序更大且更复杂,几乎可以使它更快。 The programmer must decide on an appropriate balance.... The basic rule, which has been repeated by many programmers and with which I wholeheartedly agree, is to not worry about efficiency until you know for sure that the program is too slow. 程序员必须决定一个适当的平衡...。许多程序员都重复了这一基本规则,我衷心同意这一基本规则,那就是不必担心效率,直到您确定程序太慢为止。 If it is, find out which parts are taking up the most time, and start exchanging elegance for efficiency in those parts. 如果是的话,找出哪些零件占用最多的时间,然后开始将优雅换成这些零件的效率。

Having easy to read code is key to my issue here, so I'm going to stick with the modular approach even if there is a slightly longer lookup chain for variables and functions. 易于阅读的代码是这里问题的关键,因此,即使变量和函数的查找链稍长,我仍将坚持使用模块化方法。 Either method seems to have pros and cons as it is. 每种方法似乎都具有正反方面的优点和缺点。

On the one hand, you have the global scope which holds several variables from the start. 一方面,您具有全局范围,从一开始就拥有多个变量。 If you put all of your code right in the global scope, your list of variables in that scope will include your own as well as variables like innerWidth and innerHeight. 如果将所有代码放在全局范围内,则该范围内的变量列表将包括您自己的变量以及innerWidth和innerHeight等变量。 The list to search through when referencing variables will be longer, but I believe this is such a small amount of overhead it is ridiculous to worry about. 引用变量时要搜索的列表会更长,但是我认为这是一个很小的开销,令人担忧。

On the other hand, you can add just one object to the global scope which holds all of the variables you want to work with. 另一方面,您可以只向全局范围添加一个对象,该对象包含要使用的所有变量。 From inside this scope, you can reference these variables easily and avoid searching through global variables like innerWidth and innerHeight. 在此范围内,您可以轻松地引用这些变量,并避免搜索诸如innerWidth和innerHeight之类的全局变量。 The con is that when accessing your encapsulated variables from the global scope you would have a longer lookup chain such as: globalscope.customscope.myvar instead of globalscope.myvar or just myvar. 缺点是,从全局范围访问封装的变量时,您将拥有更长的查找链,例如:globalscope.customscope.myvar而不是globalscope.myvar或仅是myvar。

When I look at it this way, it seems like a very trivial question. 当我这样看时,这似乎是一个非常琐碎的问题。 Perhaps the best way to go about it is to just encapsulate things that go together just for the sake of decluttering code and keep focus on readability rather than having a mess of unreadable code that is only slightly more efficient. 也许最好的方法是封装在一起的东西,只是为了使代码混乱,并专注于可读性,而不是使混乱的不可读代码效率更高。

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

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