简体   繁体   English

JavaScript内部功能和性能

[英]JavaScript inner-functions and Performance

What is the impact on running-time and memory defining a clousre vs. global-scope function? 对定义clousre与全局范围函数的运行时和内存有什么影响?

function a(){
      //functions (option A)
}
//functions(option B)

I understand that Option A has the advantage of function-a-scope(Closure)... 我知道选项A具有功能范围(Closure)的优势......

lets say that I have 1000 functions, how would that impact both running time and memory? 让我说我有1000个功能,这会如何影响运行时间和内存?

If you use inner functions, the run time has to allocate and save their contexts for any future invocation, and this happens each time the function containing them gets called. 如果使用内部函数,则运行时必须为将来的调用分配和保存它们的上下文,并且每次调用包含它们的函数时都会发生这种情况。 As a result, it is convenient to imagine that declaring an inner function works like constructing an object, whose members are simply the variables in the enclosing scope around that function. 因此,可以很方便地设想声明一个内部函数就像构造一个对象一样,该对象的成员只是围绕该函数的封闭范围内的变量。

This may not be all that bad if you do it infrequently, since the amount of memory is about the same as allocating an object on the heap; 如果不经常这样做,这可能不是那么糟糕,因为内存量与在堆上分配对象大致相同; (and there are some clever optimizations you can do to avoid this in some cases, for example if you only pass the function down the call stack you can allocate in the local stack space, or do some inlining etc.). (在某些情况下,您可以采取一些巧妙的优化来避免这种情况,例如,如果您只在调用堆栈中传递函数,则可以在本地堆栈空间中分配,或者执行一些内联​​等)。 However, in most circumstances it is still an allocation, so you should avoid using too many of them in busy loops or creating many inner functions. 但是,在大多数情况下它仍然是一个分配,所以你应该避免在繁忙的循环中使用太多它们或创建许多内部函数。

So to answer your question, option B would be faster in general. 所以为了回答你的问题,选项B一般会更快。 But don't let this discourage you! 但是不要让这让你气馁!

My final take is that the convenience inner functions afford completely outweighs the small run time overhead, and I would say use them wherever convenient. 我最后的看法是方便的内部功能完全超过了小的运行时间开销,我想说在方便的地方使用它们。 If it turns out to be a performance bottleneck, go back and optimize them out. 如果它成为性能瓶颈,请返回并优化它们。

Performance 性能

A very tiny benchmark case: 一个非常小的基准案例:

#1 inner function: http://jsfiddle.net/bMHgc/ #1内部功能: http//jsfiddle.net/bMHgc/

#2 function outside: http://jsfiddle.net/sAVZn/ 外面的#2功能: http//jsfiddle.net/sAVZn/

At my machine: (5000 * 1000 times) 在我的机器上:(5000 * 1000次)

#1 - 700ms #1 - 700毫秒

#2 - 80ms #2 - 80ms

Memory 记忆

They are almost the same ... 它们差不多......

I would recommend option A, if possible, since it can make your code cleaner. 如果可能的话,我会推荐选项A,因为它可以使您的代码更清晰。

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

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